40.3.11 使用Spock测试Spring Boot应用

如果想使用Spock测试Spring Boot应用,你需要为应用添加Spock的spock-spring依赖,该依赖已将Spring测试框架集成进Spock,怎么使用Spock测试Spring Boot应用取决于你使用的Spock版本。

Spring Boot为Spock 1.0提供依赖管理,如果希望使用Spock 1.1,你需要覆盖build.gradlepom.xml文件中的spock.version属性。

当使用Spock 1.1时,只能使用上述注解,你可以使用@SpringBootTest注解你的Specification以满足测试需求。

当使用Spock 1.0时,@SpringBootTest将不能用于web项目,你需要使用@SpringApplicationConfiguration@WebIntegrationTest(randomPort = true)。 不能使用@SpringBootTest也就意味着你失去了自动配置的TestRestTemplate bean,不过可以通过以下配置创建一个等价的bean:

@Configuration
static class TestRestTemplateConfiguration {

    @Bean
    public TestRestTemplate testRestTemplate(
            ObjectProvider<RestTemplateBuilder> builderProvider,
            Environment environment) {
        RestTemplateBuilder builder = builderProvider.getIfAvailable();
        TestRestTemplate template = builder == null ? new TestRestTemplate()
                : new TestRestTemplate(builder.build());
        template.setUriTemplateHandler(new LocalHostUriTemplateHandler(environment));
        return template;
    }

}

Last updated