如何在JUnit测试中正确模拟FeignClient响应 [英] How to properly emulate FeignClient responses in JUnit tests

查看:1241
本文介绍了如何在JUnit测试中正确模拟FeignClient响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用FeignClient在微服务之间进行通信.我想测试一个微服务,而不运行,因此我需要某种方式来模拟它的响应.这时候我在嘲笑feignClient.但是,在这种情况下模拟FeignClient的响应是否正确?

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?

我的FeignClient:

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

}

我的测试:

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

        //...

    }
}

推荐答案

为假客户编写单元测试没有多大意义,因此唯一的测试方法是编写集成测试.对于http客户端的集成测试,您可能需要使用以下两种方法之一:

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)如果您无法控制正在呼叫的服务,可以使用 wiremock 来模拟服务响应.在那种情况下,您将创建真正的bean,并真正通过HTTP来模拟服务器.它支持各种类型的存根.

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)如果您可以控制要调用的服务,则可能要应用消费者驱动合同"方法并利用春季云合约

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

这篇关于如何在JUnit测试中正确模拟FeignClient响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆