40.4.4 TestRestTemplate

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

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_PORTWebEnvironment.DEFINED_PORT属性,你可以注入一个配置完全的TestRestTemplate,并开始使用它。如果有需要,你还可以通过RestTemplateBuilder bean进行额外的自定义:

@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(...);
        }

    }

}

Last updated