簡體   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