java - 如何配置Spring TestRestTemplate

标签 java spring rest spring-data-rest

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

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

这是我的 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 不考虑 application.properties 中的 spring.data.rest.base-path首先? beeing complete preconfigured 的想法不是这个包装类的整个用例吗?

医生说

If you are using the @SpringBootTest annotation, a TestRestTemplate is automatically available and can be @Autowired into you test. If you need customizations (for example to adding additional message converters) use a RestTemplateBuilder @Bean.

完整的 Java 代码示例看起来如何?

最佳答案

我知道这是一个老问题,您现在可能已经找到了另一个解决方案。但无论如何,我正在为其他像我一样绊倒的人回答。我有一个类似的问题,并最终在我的测试类中使用 @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
        }
    }

关于java - 如何配置Spring TestRestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42272521/

相关文章:

spring - 使用 Corda 运行 Spring 服务器时出现 Quasar 错误

ruby - RestClient.send 在哪里定义?

java - java 和 javafx 之间有什么最大的区别

Java 泛型 - 删除机制

java - Appengine 没有编译我的 .jspx 文件

java - 在java中创建要在restful webservice中返回的XML数据

rest - 何时在 RESTful API 中使用路径参数与查询参数?

java - 如何使用 java-selenium webdriver 检查 zip 文件是否已成功下载?

java - 通过 javax.inject.Provider 进行 Spring 注入(inject)太慢

Spring 启动/Tomcat, "Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean"