用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
# 40.4.4 TestRestTemplate 在集成测试中,`TestRestTemplate`是Spring `RestTemplate`的便利替代。你可以获取一个普通的或发送基本HTTP认证(使用用户名和密码)的模板,不管哪种情况, 这些模板都有益于测试:不允许重定向(这样你可以对响应地址进行断言),忽略cookies(这样模板就是无状态的),对于服务端错误不会抛出异常。推荐使用Apache HTTP Client\(4.3.2或更高版本\),但不强制这样做,如果相关库在classpath下存在,`TestRestTemplate`将以正确配置的client进行响应。 ```java public class MyTest { RestTemplate template = new TestRestTemplate(); @Test public void testRequest() throws Exception { HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders(); assertThat(headers.getLocation().toString(), containsString("myotherhost")); } } ``` 如果正在使用`@SpringBootTest`,且设置了`WebEnvironment.RANDOM_PORT`或`WebEnvironment.DEFINED_PORT`属性,你可以注入一个配置完全的`TestRestTemplate`,并开始使用它。如果有需要,你还可以通过`RestTemplateBuilder` bean进行额外的自定义: ```java @RunWith(SpringRunner.class) @SpringBootTest public class MyTest { @Autowired private TestRestTemplate template; @Test public void testRequest() throws Exception { HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders(); assertThat(headers.getLocation().toString(), containsString("myotherhost")); } @TestConfiguration static class Config { @Bean public RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder() .additionalMessageConverters(...) .customizers(...); } } } ```