我有一个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.但是,静态类中我无法访问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
采取spring.data.rest.base-path
从application.properties
考虑在第一位?这个包装类的整个用例是不是完全预配置的想法?
的文档赛斯
如果您使用的是@SpringBootTest注解,一个TestRestTemplate是 自动可用和可@Autowired到你的测试。如果您需要定制(例如添加附加消息 转换器),请使用RestTemplateBuilder @Bean。
在完整的Java代码示例中,这看起来如何?