40.4.4 TestRestTemplate

在集成测试中,TestRestTemplate是Spring RestTemplate的便利替代。你可以获取一个普通的或发送基本HTTP认证(使用用户名和密码)的模板,不管哪种情况,
这些模板都有益于测试:不允许重定向(这样你可以对响应地址进行断言),忽略cookies(这样模板就是无状态的),对于服务端错误不会抛出异常。推荐使用Apache HTTP Client(4.3.2或更高版本),但不强制这样做,如果相关库在classpath下存在,TestRestTemplate将以正确配置的client进行响应。

  1. public class MyTest {
  2. RestTemplate template = new TestRestTemplate();
  3. @Test
  4. public void testRequest() throws Exception {
  5. HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders();
  6. assertThat(headers.getLocation().toString(), containsString("myotherhost"));
  7. }
  8. }

如果正在使用@SpringBootTest,且设置了WebEnvironment.RANDOM_PORTWebEnvironment.DEFINED_PORT属性,你可以注入一个配置完全的TestRestTemplate,并开始使用它。如果有需要,你还可以通过RestTemplateBuilder bean进行额外的自定义:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class MyTest {
  4. @Autowired
  5. private TestRestTemplate template;
  6. @Test
  7. public void testRequest() throws Exception {
  8. HttpHeaders headers = template.getForEntity("http://myhost.com", String.class).getHeaders();
  9. assertThat(headers.getLocation().toString(), containsString("myotherhost"));
  10. }
  11. @TestConfiguration
  12. static class Config {
  13. @Bean
  14. public RestTemplateBuilder restTemplateBuilder() {
  15. return new RestTemplateBuilder()
  16. .additionalMessageConverters(...)
  17. .customizers(...);
  18. }
  19. }
  20. }