如何在不提供服务的情况下测试Feign REST客户端?

时间:2018-08-12 09:59:54

标签: rest junit mocking client feign

我有简单的REST客户端:

   @FeignClient(name = "${service-parameters.name}", url = "${service-parameters.url}")
public interface ParametersClient {

@GetMapping("api/v1/parameters/by-site-id/{parameterName}/{siteId}")
Parameter getParameterBySiteId(
        @PathVariable(name = "parameterName") final String parameterName,
        @PathVariable(name = "siteId") final Long siteId,
        @RequestParam(name = "validityDate", required = false) LocalDate validityDate);

@GetMapping("api/v1/parameters/by-client-id/{parameterName}/{clientId}")
Parameter getParameterByClientId(
        @PathVariable(name = "parameterName") final String parameterName,
        @PathVariable(name = "clientId") final Long clientId,
        @RequestParam(name = "validityDate", required = false) LocalDate validityDate);

}

但是我无法在测试中接触一项服务。所以我需要测试客户端中我的方法创建的请求。其他所有内容都在服务端进行了测试。

这些是我提供服务的正确要求: http://localhost:8080/api/v1/parameters/by-site-id/PSEUDO_ONLINE_ROOT_PATH/3000001?validityDate=2018-07-18

http://localhost:8080/api/v1/parameters/by-client-id/KOMBI_MINIMUM_NUMBER_GROUP/10508078

在不运行服务的情况下测试客户端的最佳方法是什么?我花了很多时间进行搜索,但没有发现对我的案子有用的东西:(。

非常感谢您提供任何建议。

1 个答案:

答案 0 :(得分:1)

我已经通过以下代码解决了我的问题:

@AutoConfigureMockMvc
@SpringBootTest
@RunWith(JUnitPlatform.class)
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
public class ParameterClientTest {

private final RestTemplate restTemplate = new RestTemplate();

@Autowired
ParametersClient client;

private final MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).bufferContent().build();

@Test
public void getParameterBySiteId() {
    mockServer.expect(once(), requestTo(REQUEST_BY_SITE_ID)).andRespond(withSuccess(RESPONSE_BY_SITE_ID, MediaType.APPLICATION_JSON));
    Response result = client.getParameterBySiteId(PSEUDO_ONLINE_ROOT_PATH, SITE_ID, VALIDITY_DATE);
    assertEquals(REQUEST_BY_SITE_ID, result.request().url());
}

@Test
public void getParameterByClientId() {
    mockServer.expect(once(), requestTo(REQUEST_BY_CLIENT_ID)).andRespond(withSuccess(RESPONSE_BY_CLIENT_ID, MediaType.APPLICATION_JSON));
    Response result = client.getParameterByClientId(KOMBI_MINIMUM_NUMBER_GROUP, CLIENT_ID, VALIDITY_DATE);
    assertEquals(REQUEST_BY_CLIENT_ID, result.request().url());
}

}