2017-02-16 62 views
2

我有一个REST(spring-hateoas)服务器,我想用JUnit测试来测试。因此我使用自动注入的TestRestTemplate如何配置Spring TestRestTemplate

但是,我现在如何添加一些更多的配置到这个预配置的TestRestTemplate?我需要配置rootURI并添加拦截器。

Thisi是我的JUnit测试类:

@RunWith(SpringRunner.class) 
@ActiveProfiles("test") 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)  

public class RestEndpointTests { 
    private Logger log = LoggerFactory.getLogger(this.getClass()); 

    @LocalServerPort 
    int localServerPort; 

    @Value(value = "${spring.data.rest.base-path}") // nice trick to get basePath from application.properties 
    String basePath; 

    @Autowired 
    TestRestTemplate client; // how to configure client? 

    [... here are my @Test methods that use client ...] 
} 

The documentation sais that a static @TestConfiguration class can be used.但是,静态类中我无法访问localServerPortbasePath

@TestConfiguration 
    static class Config { 

    @Bean 
    public RestTemplateBuilder restTemplateBuilder() { 
     String rootUri = "http://localhost:"+localServerPort+basePath; // <=== DOES NOT WORK 
     log.trace("Creating and configuring RestTemplate for "+rootUri); 
     return new RestTemplateBuilder() 
     .basicAuthorization(TestFixtures.USER1_EMAIL, TestFixtures.USER1_PWD) 
     .errorHandler(new LiquidoTestErrorHandler()) 
     .requestFactory(new HttpComponentsClientHttpRequestFactory()) 
     .additionalInterceptors(new LogRequestInterceptor()) 
     .rootUri(rootUri); 
    } 

    } 

我最重要的问题是:为什么不TestRestTemplate采取spring.data.rest.base-pathapplication.properties考虑在第一位?这个包装类的整个用例是不是完全预配置的想法?

的文档赛斯

如果您使用的是@SpringBootTest注解,一个TestRestTemplate是 自动可用和可@Autowired到你的测试。如果您需要定制(例如添加附加消息 转换器),请使用RestTemplateBuilder @Bean。

在完整的Java代码示例中,这看起来如何?

回答

1

我知道这是一个老问题,现在你可能已经找到了另一个解决方案。但无论如何,其他人都像我一样磕磕碰碰。我有一个类似的问题,并最终在我的测试类中使用@PostConstruct来构建一个按我的喜好配置的TestRestTemplate,而不是使用@TestConfiguration。

@RunWith(SpringJUnit4ClassRunner.class) 
    @EnableAutoConfiguration 
    @SpringBootTest(classes = {BackendApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
    public class MyCookieClientTest { 
     @LocalServerPort 
     int localPort; 

     @Autowired 
     RestTemplateBuilder restTemplateBuilder; 

     private TestRestTemplate template; 

     @PostConstruct 
     public void initialize() { 
      RestTemplate customTemplate = restTemplateBuilder 
       .rootUri("http://localhost:"+localPort) 
       .... 
       .build(); 
      this.template = new TestRestTemplate(customTemplate, 
       null, null, //I don't use basic auth, if you do you can set user, pass here 
       HttpClientOption.ENABLE_COOKIES); // I needed cookie support in this particular test, you may not have this need 
     } 
    }