1

我无法从 Feign Client 那里得到嘲笑的回应。我在代码下方提供。

在服务类中,已经这样写了。

public String getInfo(HttpServletRequest request, String id, String type) {
        .... other code .....
        try {
            
            statusAsJsonString = myFeignClient.getStatus(cookie, id, type);
            System.out.println("statusAsJsonString--------->"+statusAsJsonString);
            ObjectNode node = new ObjectMapper().readValue(statusAsJsonString, ObjectNode.class);
            if (node.has(CommonConstants.STATUS)) {
                statusValue = node.get(CommonConstants.STATUS).asText();
            }
        } catch (FeignException fe) {
            byte[] contents = fe.content();
            String jsonContents  = null;
            if(contents != null) {
                jsonContents = new String(contents);
            }
            statusValue = getErrorParsedStatusValue(jsonContents);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        log.debug("status: " + statusValue);
        return statusValue;
    }

在单元测试中,我尝试用以下方式编写。

String responseBody = "[]";
when(myFeignClient.getStatus("cookievalue", "id", "SOme-Value")).thenReturn(responseBody);

我也使用过,WireMock 来实现它。

wireMockServer.stubFor(WireMock.get("/rest/v1/somna/{id}/phase").withRequestBody(WireMock.equalToJson("{ \"name\": \"Phone\", \"initialStock\": 3}"))
                .willReturn(WireMock.okJson(responseBody)));

以下代码永远不会被覆盖和执行。

statusAsJsonString = myFeignClient.getStatus(cookie, id, type);
System.out.println("statusAsJsonString--------->"+statusAsJsonString);

Feign客户端的调用也是在服务方法内部,首先要获取该Feign客户端的模拟结果。请帮我。

我在我的 Feign 客户端下面提供

@FeignClient(name = CommonConstants.FEIGN_CLIENT_NAME, url = "${feign.service.url}", primary = false)
public interface MyFeignClient {

    @GetMapping(value = "/rest/v1/project/{id}/phaseName")
    String getStatus(@RequestHeader("Cookie") String cookie,
            @PathVariable("id") Stringid, @RequestParam("type") String type);

}

在我的测试课中,我添加了以下内容。

@Autowired
    private MyServiceImpl readyService = new MyServiceImpl();
    
     @Mock
    private MyFeignClient myFeignClient;
    
    @ClassRule
    public static WireMockServer wireMockServer = new WireMockServer(new WireMockConfiguration().port(8088));
    
    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);
        httpServletRequest = Mockito.mock(HttpServletRequest.class);
        ReflectionTestUtils.setField(someService, "cookieName", "cookieName");
        
        wireMockServer.start();

    }
4

0 回答 0