繁体   English   中英

使用Mockito模拟HttpURLConnection的问题

[英]Issues with Mocking HttpURLConnection using Mockito

我正在尝试模拟HttpURLConnection对象,但似乎无法正确处理。 这是我要测试的方法。

@Override
public JSON connect() throws IOException {
    HttpURLConnection httpConnection;
    String finalUrl = url;
    URL urlObject = null;
    int status = 0;
    //recursively check for redirected uri if the given uri is moved
    do{
            urlObject = getURL(finalUrl);
            httpConnection = (HttpURLConnection) urlObject.openConnection();
            //httpConnection.setInstanceFollowRedirects(true);
            //httpConnection.connect();
            status = httpConnection.getResponseCode();
            if (300 > status && 400 < status){
                continue;
            }
            String redirectedUrl =    httpConnection.getHeaderField("Location");
            if(null == redirectedUrl){
                    break;
            }
            finalUrl =redirectedUrl;

    }while (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK);
    return  JSONSerializer.toJSON(getData(httpConnection).toString());
}

这是我所做的。

 @Before
public void setUp() throws Exception{
    //httpConnectGithubHandle = new HttpConnectGithub(VALID_URL);
    httpConnectGithubHandle = mock(HttpConnectGithub.class);
    testURL               = new URL(VALID_URL);
    mockHttpURLConnection = mock(HttpURLConnection.class);  
    mockInputStreamReader = mock(InputStreamReader.class);
    mockBufferedReader    = mock(BufferedReader.class);
    mockInputStream       = mock(InputStream.class);
    when(httpConnectGithubHandle.getData(mockHttpURLConnection)).thenReturn(SOME_STRING);
    when(httpConnectGithubHandle.getURL(SOME_STRING)).thenReturn(testURL);
    when(mockHttpURLConnection.getResponseCode()).thenReturn(200);
    when(mockHttpURLConnection.getHeaderField(LOCATION)).thenReturn(SOME_STRING);
    PowerMockito.whenNew(InputStreamReader.class)
    .withArguments(mockInputStream).thenReturn(mockInputStreamReader);
    PowerMockito.whenNew(BufferedReader.class)
      .withArguments(mockInputStreamReader).thenReturn(mockBufferedReader);  
    PowerMockito.when(mockBufferedReader.readLine())
    .thenReturn(JSON_STRING)
    .thenReturn(null);
}

那就是我的setUp方法。 此方法调用的方法的测试用例成功。 我的实际测试用例如下。

 @Test
    public void testConnect() throws IOException {
        JSON jsonObject = httpConnectGithubHandle.connect();
        System.out.println(jsonObject);
        assertThat(jsonObject, instanceOf(JSON.class));
    }

我试图打印数据,它显示为空。

目前,您仅在测试模拟。 在模拟上调用httpConnectGithubHandle.connect() ,并且模拟未返回任何行为,因此模拟返回null。 您应该在测试中使用真实的HttpConnectGithub对象。 (取消注释测试的第一行,并删除HttpConnectGithub模拟。)

暂无
暂无

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

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