繁体   English   中英

测试失败,因为实体始终为空

[英]Test fails as entity is always null

我的 Java 应用程序中有这个方法:

public HttpEntity getConfirm(String confirmUrl, String cookie) throws IOException {

        LOG.debug("getConfirm triggered");
        HttpGet req = null;

        try {

            HttpClient client = HttpClientBuilder.create().build();
            req = new HttpGet(confirmUrl);

            req.addHeader("User-Agent", "Apache HTTPClient");
            req.addHeader("Cookie", cookie);
            HttpResponse res = client.execute(req);

            HttpEntity entity = res.getEntity();
            int statusLine = res.getStatusLine().getStatusCode();
            HttpEntity entity = res.getEntity();
            int statusLine = res.getStatusLine().getStatusCode();

            String content = EntityUtils.toString(entity);
            LOG.info(content + "" + statusLine);
            return entity;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (req != null) {

                req.releaseConnection();
            }

            return null;
        }
    }

创建此单元测试是为了对其进行测试:

@Test
public void getConfirmSuccess() throws IOException {

    HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenReturn(200);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    HttpEntity entity = mock(HttpEntity.class);
    InputStream stream = new ByteArrayInputStream("{\n\"state\": \"success\",\n\"message\": \"My message.\"\n}".getBytes("UTF-8"));
    when(entity.getContent()).thenReturn(stream);
    when(httpResponse.getEntity()).thenReturn(mock(HttpEntity.class));

    ReissueCertService reissueCertService = new ReissueCertServiceReal();

    assertEquals(reissueCertService.reissueCert("http://testurl", "foo"), httpResponse);
}

测试失败,因为entity = response.getEntity(); 为空,因此实体永远不会被赋值。 我想我需要做一个when(entity).thenReturn(...)但我不确定我应该返回什么。 这是正确的,如果是这样,我应该在这里返回什么?

当您编写模拟对象的返回行为时,您可以在 Mock 中做两件事。

返回我们拥有的引用的模拟对象:

when(httpResponse.getStatusLine()).thenReturn(statusLine);

如果你在这里看到,我们返回一个 statusLine 的模拟对象(我们有谁的参考),如果我们这样做,我们将受益于选择 statusLine 的行为,如下所示:

  when(statusLine.getStatusCode()).thenReturn(200);

下面是另一种方法,当我们不关心要返回的模拟对象的引用时:

when(httpResponse.getStatusLine()).thenReturn(StatusLine.class);

如果你在这里看到,我们正在返回一个 statusLine 的模拟对象,我们不持有它的引用,所以我们不能为它编写模拟行为,这在第一个示例中能够做到。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM