您可以创建一个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 配置您自己的 TestRestTemplate(您可以在 @987654332 中看到此代码@)。以下是后一种方法的示例:
@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 并成功地调用了本地主机上的 Spring Boot 应用程序:
@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());
}
}