与 spock 的集成测试。在第一次测试之前加载上下文
Integration test with spock. Load context before first test
让我们考虑一个非常简单的例子来证明我的观点:
@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
测试。
是否可以创建上下文 "at the very beginning" ?为了在 getCarById(_)
方法中访问它(和 carService
)?
您的示例的问题是您试图从 where
块中的上下文访问 CarService
实例。 where
块中的代码用于在早期阶段创建多个测试,非常接近 class 加载。
我建议只用汽车 ID 替换 Car
参数。然后在 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
}
}
让我们考虑一个非常简单的例子来证明我的观点:
@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
测试。
是否可以创建上下文 "at the very beginning" ?为了在 getCarById(_)
方法中访问它(和 carService
)?
您的示例的问题是您试图从 where
块中的上下文访问 CarService
实例。 where
块中的代码用于在早期阶段创建多个测试,非常接近 class 加载。
我建议只用汽车 ID 替换 Car
参数。然后在 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
}
}