【问题标题】:Integration test with spock. Load context before first test使用 spock 进行集成测试。在第一次测试之前加载上下文
【发布时间】:2018-11-17 14:49:49
【问题描述】:

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

@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 test。

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

【问题讨论】:

  • 将该代码放在构造函数 Tmp() 中。
  • 我不关注。你能详细说明一下吗?

标签: spring-boot integration-testing spock


【解决方案1】:

您的示例的问题是您尝试从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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多