43.3.17 自动配置的REST客户端

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

@RunWith(SpringRunner.class)
@RestClientTest(RemoteVehicleDetailsService.class)
public class ExampleRestClientTest {

    @Autowired
    private RemoteVehicleDetailsService service;

    @Autowired
    private MockRestServiceServer server;

    @Test
    public void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails()
            throws Exception {
        this.server.expect(requestTo("/greet/details"))
                .andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
        String greeting = this.service.callRestService();
        assertThat(greeting).isEqualTo("hello");
    }

}

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

最后更新于