与spock集成测试。首次测试前加载上下文

问题描述 投票:0回答:1

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

@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(_))?

spring-boot integration-testing spock
1个回答
3
投票

您的示例的问题是您尝试从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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.