我有一個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代碼示例中,這看起來如何?