40.3.9 自动配置的REST客户端

你可以使用@RestClientTest测试REST客户端,它默认会自动配置Jackson和GSON,配置RestTemplateBuilder,并添加MockRestServiceServer支持。你需要将@RestClientTestvaluecomponents属性值设置为待测试类:

  1. @RunWith(SpringRunner.class)
  2. @RestClientTest(RemoteVehicleDetailsService.class)
  3. public class ExampleRestClientTest {
  4. @Autowired
  5. private RemoteVehicleDetailsService service;
  6. @Autowired
  7. private MockRestServiceServer server;
  8. @Test
  9. public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails()
  10. throws Exception {
  11. this.server.expect(requestTo("/greet/details"))
  12. .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
  13. String greeting = this.service.callRestService();
  14. assertThat(greeting).isEqualTo("hello");
  15. }
  16. }

附录中可以查看@RestClientTest启用的自动配置列表。