Search code examples
restjunitmockingclientfeign

How to test Feign REST client without acces to servise?


I have simple REST client:

   @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);

}

but I am not able to touch a service in my test. So I need to test request which my methods in client create. Everything else is tested on service side.

Those are correct requests for my servise: 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

What is the best way to test my client without running service? I spent a lot of time of searching but I did not find anything useful for my case :(.

Thanks a lot for any advice.


Solution

  • I have solved my problem with folowing code:

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

    }