【发布时间】:2017-02-16 11:21:47
【问题描述】:
我有一个 REST (spring-hateoas) 服务器,我想通过 JUnit 测试对其进行测试。因此我使用的是自动注入的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. 但在那个静态类中我无法访问localServerPort 或basePath:
@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?蜜蜂的想法不是完全预配置的,这个包装类的整个用例吗?
文档说
如果你使用@SpringBootTest 注解,TestRestTemplate 是 自动可用并且可以@Autowired 进入你的测试。如果你 需要自定义(例如添加额外的消息 转换器)使用 RestTemplateBuilder @Bean。
在完整的 Java 代码示例中看起来如何?
【问题讨论】:
标签: java spring rest spring-data-rest