Junit无法返回模拟的响应并以null返回

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

我是Mockito的新手,并尝试模拟Web服务响应,我确实在某种程度上尝试了模拟,但很少有对象可以工作,但是最后模拟的WebResponse始终返回null。

我要测试的服务方法:getWebResponse方法

public WebResponse getWebResponse(String crmNumber) throws JSONException, ExecutionException, WebException {
    Map<String, String> HEADERS_POST = new HashMap<String, String>() {
        {
            put(WebUtil.HEADER_CONTENT, WebUtil.CONTENT_JSON);
            put(WebUtil.HEADER_ACCEPT, WebUtil.CONTENT_JSON);
        }
    };
    JSONObject requestJson = new JSONObject();
    requestJson.put("crmNumber", crmNumber);
    requestJson.put("application", "ABCD");
    requestJson.put("feature", "DDDFL");
    // Using internal web service becuase device authentication is done separately.
    String url = CommonUtil.getServiceBaseUrl(true) + "/ett";
    WebServiceClient client = WebServiceClientRegistry.getClient(ApacheCustom.class);
    WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, url, HEADERS_POST, requestJson.toString());
    // Till here i m getting all mocked object (client also Mocked) after this stament the webRes is returning null;
    WebResponse webRes = client.doRequest(webReq);
    return webRes;
}

这里是测试方法:

@Test
public void getWebResponseTest() {
    mockStatic(CommonUtil.class);
    mockStatic(WebServiceClientRegistry.class);
    this.webResponse = new GenericWebResponse(200, "", new HashMap(), "");

    try {
        Mockito.when(CommonUtil.getServiceBaseUrl(true)).thenReturn("https://stage.com/service");
        WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, "https://stage.com/service", new HashMap(), "");
        Mockito.when(WebServiceClientRegistry.getClient(ApacheCustom.class)).thenReturn(client);
        Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
        WebResponse wesponse = this.ServiceResponse.getWebResponse("Number");
        Assert.assertEquals(wesponse.getStatusCode(), 200);
    } catch (Exception e) {
        Assert.fail();
    }
}

但是Test类的getWebResonse方法始终返回null响应(即使已被模拟)]]

我是Mockito的新手,试图模拟Web服务响应,但我确实在某种程度上尝试了模拟,但很少有Objects可以工作,但是最后模拟的WebResponse始终返回null。服务方式我是...

unit-testing junit mockito powermockito
1个回答
0
投票

您模拟client.doRequest如下:

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