问题
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));
//...
}
}
回答1:
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
来源:https://stackoverflow.com/questions/57328839/how-to-properly-emulate-feignclient-responses-in-junit-tests