与spock的集成测试.在第一次测试之前加载上下文



让我们考虑一个非常简单的例子来证明我的观点:

@SpringBootTest
class Tmp extends Specification{
@Autowired
private CarService carService;
def "getCarById"(int id) {
return carService != null ? carService.getById(id) : new Car();
}
def "validate number of doors"(Car car, int expectedNrOfDoors) {
expect:
car.getNrOfDoors() == expectedNrOfDoors
where:
car               || expectedNrOfDoors
getCarById(1)     || 3
getCarById(2)     || 3
getCarById(3)     || 5
}
}

将调用第一个getCarById(_)方法。然后将创建上下文,然后执行validate number of doors测试

是否可以在"一开始"创建上下文?以便在getCarById(_)方法中访问它(和carService(?

示例的问题在于,您试图从where块中的上下文访问CarService实例。where块中的代码用于在早期阶段创建多个测试,非常接近类加载。

我建议将Car参数仅替换为汽车ID。然后在given块中调用getCarById。届时,上下文将被加载,carService是可访问的。

@SpringBootTest
class Tmp extends Specification {
@Autowired
private CarService carService
def "validate number of doors"(int carId, int expectedNrOfDoors) {
given:
Car car = carService.getById(carId)
expect:
car.getNrOfDoors() == expectedNrOfDoors
where:
carId || expectedNrOfDoors
1     || 3
2     || 3
3     || 5
}
}

最新更新