让我们考虑一下非常简单的例子来说明我的观点:
@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
测试。
是否有可能“在一开始”创建上下文?为了能够在carService
方法中访问它(以及getCarById(_)
)?
您的示例的问题是您尝试从CarService
块中的上下文访问where
实例。来自where
块的代码用于在早期阶段创建多个测试,非常接近类加载。
我建议用汽车ID替换Car
参数。然后你在getCarById
区块中调用given
。那时上下文将加载一个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
}
}