您可以创建一个TestRestTemplate
,并使用@Bean
注释将其呈现给Spring。
例如:
@Bean
@Primary
public TestRestTemplate testRestTemplate() {
RestTemplate restTemplate = new RestTemplateBuilder()
.errorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}).build();
return new TestRestTemplate(restTemplate, user, password, TestRestTemplate.HttpClientOption.ENABLE_REDIRECTS, TestRestTemplate.HttpClientOption.ENABLE_COOKIES);
}
或者,如果您不需要定制RestTemplate
然后使用下面的构造函数(它在内部实例为您RestTemplate
):
@Bean
@Primary
public TestRestTemplate testRestTemplate() {
return new TestRestTemplate(TestRestTemplate.HttpClientOption.ENABLE_REDIRECTS, TestRestTemplate.HttpClientOption.ENABLE_COOKIES);
}
更新1来解决此评论:
当我运行我的测试,现在我得到以下错误org.apache.http.ProtocolException: Target host is not specified
Spring提供的TestRestTemplate
被配置为解决相对于http://localhost:${local.server.port}
路径。因此,当您用自己的实例替换Spring提供的实例时,您需要提供完整的地址(包括主机和端口)或者配置LocalHostUriTemplateHandler
(您可以在org.springframework.boot.test.context.SpringBootTestContextCustomizer.TestRestTemplateFactory
中看到此代码)来配置您自己的TestRestTemplate
。下面是后一种方法的一个例子:
@Bean
@Primary
public TestRestTemplate testRestTemplate(ApplicationContext applicationContext) {
RestTemplate restTemplate = new RestTemplateBuilder()
.errorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}).build();
TestRestTemplate testRestTemplate =
new TestRestTemplate(restTemplate, user, password, TestRestTemplate.HttpClientOption
.ENABLE_REDIRECTS, TestRestTemplate.HttpClientOption.ENABLE_COOKIES);
// let this testRestTemplate resolve paths relative to http://localhost:${local.server.port}
LocalHostUriTemplateHandler handler =
new LocalHostUriTemplateHandler(applicationContext.getEnvironment(), "http");
testRestTemplate.setUriTemplateHandler(handler);
return testRestTemplate;
}
有了这个bean配置以下测试案例使用了定制的TestRestTemplate
并成功调用本地主机上的春天启动的应用程序:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RestTemplateTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void test() {
ResponseEntity<String> forEntity = this.restTemplate.getForEntity("/some/endpoint", String.class);
System.out.println(forEntity.getBody());
}
}
这将导致更多的问题。首先,我需要在'testRestTemplate()'中添加'@ Primary',另外注册两个bean。其次,当我运行测试时,我现在得到以下错误:org.apache.http.ProtocolException:未指定目标主机。我认为在创建TestRestTemplate时,spring-boot会有更多的魔力。 – jax
@jax道歉,我已经更新了这个问题,以澄清如何使用定制的'TestRestTemplate'以及如何使用它,就像你使用Spring提供的'TestRestTemplate'一样。 – glytching