0

I have Real FeignClient which returns some objects from remote endpoint.

However before i start asking for new service i need to test my entity / logic first. I decided to create fake mock service which will return objects i need (5 max).

How can i fake FeignClient in SpringBoot?

giliermo
  • 141
  • 1
  • 8
  • Does this answer your question? [Mock an Eureka Feign Client for Unittesting](https://stackoverflow.com/questions/34397570/mock-an-eureka-feign-client-for-unittesting) – pvpkiran Apr 21 '20 at 15:16
  • No . author of that post is talking about testing. i want just another class which will be mock service. – giliermo Apr 21 '20 at 15:20

2 Answers2

1

You can use the @Primary annotation to override the default implementation.

In your java configuration file:

@Bean
@Primary // this anotation will override the system implementation
public FeignClient feignClient() {
 // create and return a fake FeignClient here.
return MyFakeImplementationFeignClient();
}
Lucbel
  • 339
  • 1
  • 4
1

You could use the real FeignClient, but let it talk to a dummy server.

An easy dummy server is Wiremock, that you can start up in your java code or as a standalone java main class:

http://wiremock.org/docs/java-usage/

WireMockServer wireMockServer = new WireMockServer("localhost", 8090);
wireMockServer.start();
WireMock.configureFor("localhost", 8090);
WireMock.stubFor(get(urlEqualTo("/somethings"))
    .willReturn(aResponse()
            .withBodyFile("path/to/test.json")));

Once this is started up and configured, use http://localhost:8090 in your FeignClient.

A major advantage is that you can immediately implement/test the JSON or HTTP mappings as well, so you're sure the FeignClient is configured correctly, too. You can even simulate errors or delays:

WireMock.stubFor(get(urlEqualTo("/somethings")).willReturn(
        aResponse()
                .withStatus(503)
                .withFixedDelay(10_000)));
GeertPt
  • 16,398
  • 2
  • 37
  • 61
  • can wiremock return entities? – giliermo Apr 22 '20 at 08:19
  • wiremock returns HTTP responses. If you know how your entities are encoded (in json or xml), you can writy your own response body, either using .withBodyFile(filename), or .withBody(string) – GeertPt Apr 22 '20 at 13:20