2017-02-16 80 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 
     } 
    } 
相關問題