如何在 JUnit 测试中正确模拟 FeignClient 响应

问题描述 投票:0回答:1

我正在使用 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个回答
0
投票

1)如果您无法控制所调用的服务,您可以使用

wiremock

来模拟服务的响应。在这种情况下,您将创建真正的 bean,并真正通过 HTTP 来模拟服务器。它支持各种类型的存根。 2)如果您可以控制所调用的服务,您可能需要应用消费者驱动契约方法并利用

Spring云契约

© www.soinside.com 2019 - 2024. All rights reserved.