【问题标题】:How to properly emulate FeignClient responses in JUnit tests如何在 JUnit 测试中正确模拟 FeignClient 响应
【发布时间】:2019-08-02 14:48:35
【问题描述】:

我正在使用 FeignClient 进行微服务之间的通信。我想测试一个微服务而不运行另一个,所以我需要以某种方式模拟它的响应。这时候我在嘲讽feignClient。但是,在这种情况下模拟 FeignClient 的响应是正确的方法吗?

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

        //...

    }
}

【问题讨论】:

    标签: spring-boot junit mockito spring-cloud-feign


    【解决方案1】:

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

    1) 如果您无法控制所调用的服务,您可以使用wiremock 模拟来自服务的响应。在这种情况下,您将创建真正的 bean,并真正通过 HTTP 来模拟服务器。它支持各种类型的存根。

    2) 如果您可以控制所调用的服务,您可能需要应用消费者驱动合同方法并利用 Spring cloud contract

    【讨论】:

    • 我使用 JUnit 不是为了测试 FeignClient,而是为了测试我的微服务组件以获得来自其他微服务的不同响应。
    • 如果您正在为调用 feign 客户端的其他组件编写单元测试,那么您的方法可以完美运行。但是我不会让 spring bean 参与测试,您可以只使用 @Mock@InjectMocks 注释。因为如果您测试运行 spring 上下文,它们不是单元测试,而是集成测试。
    • 谢谢。您的回答很有价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多