简体   繁体   中英

How to properly emulate FeignClient responses in JUnit tests

I am using FeignClient for communication between microservices. I would like to test one microservice without running the other, so I need somehow to emulate responses from it. At this time I am mocking feignClient. However is it a right way for emulating FeignClient's responses in this situation?

My FeignClient:

@FeignClient(name="shortestPath", url="http://localhost:5000")
public interface GraphFeignClient {

    @PostMapping(path="/short")
    public List<Integer> getShortestPath(@RequestParam("source") int source,
                                         @RequestParam("target") int target,
                                         @RequestBody Graph graph);

}

My test:

@SpringBootTest
public class GraphJsonApplicationTests {

    @Mock
    GraphFeignClient graphFeignClient;

    @Autowired
    @InjectMocks
    private GraphServiceClient graphServiceClient;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSavingShortestPath() throws Exception {

        given(graphFeignClient.getShortestPath(anyInt(),anyInt(),any()))
                .willReturn(Arrays.asList(1,2,3,4,5)); 

        //...

    }
}

It doesn't make much sense to write unit tests for feign clients, so the only one way to test is to write integration tests. For integration testing of http clients you may want to use one of two approaches:

1) In case you don't have control over service that you are calling, you could use wiremock to mock responses from the service. In that case you will create real bean, and really go through HTTP to mock server. It supports various types of stubs.

2) In case you have control over service that you are calling, you may want to apply Consumer Driven Contracts approach and utilize Spring cloud contract

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM