如何配置Spring TestRestTemplate

Rob*_*ert 7 java rest spring spring-data-rest

我有一个REST(spring-hateoas)服务器,我想用JUnit测试来测试.因此我使用自动注入TestRestTemplate.

但是,我现在如何为此预先配置的TestRestTemplate添加更多配置?我需要配置rootURI并添加拦截器.

这是我的JUnit Test类:

@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 ...]
}
Run Code Online (Sandbox Code Playgroud)

文档说明@TestConfiguration可以使用静态类.但在静态类中我无法访问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);
    }

  }
Run Code Online (Sandbox Code Playgroud)

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

doc sais

如果您正在使用@SpringBootTest注释,TestRestTemplate将自动可用,并且可以@Autowired到您的测试中.如果需要自定义(例如添加其他消息转换器),请使用RestTemplateBuilder @Bean.

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

joe*_*son 11

我知道这是一个老问题,你现在可能已经找到了另一个解决方案.但无论如何,我正在回答其他人像我一样磕磕绊绊.我有一个类似的问题,最后在我的测试类中使用@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
        }
    }
Run Code Online (Sandbox Code Playgroud)