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:

  1. @Configuration
  2. static class TestRestTemplateConfiguration {
  3. @Bean
  4. public TestRestTemplate testRestTemplate(
  5. ObjectProvider<RestTemplateBuilder> builderProvider,
  6. Environment environment) {
  7. RestTemplateBuilder builder = builderProvider.getIfAvailable();
  8. TestRestTemplate template = builder == null ? new TestRestTemplate()
  9. : new TestRestTemplate(builder.build());
  10. template.setUriTemplateHandler(new LocalHostUriTemplateHandler(environment));
  11. return template;
  12. }
  13. }