2013-10-25 94 views
1

我试图嘲笑一个HttpURLConnection对象,但我似乎无法正确理解。 这里是我想测试的方法。使用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)); 
    } 

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

回答

2

目前your're只测试模拟。在模拟上调用httpConnectGithubHandle.connect(),并且模拟返回null,因为没有定义行为。你应该在你的测试中使用一个真实的HttpConnectGithub对象。 (取消注释测试的第一行并删除HttpConnectGithub模拟。)

+0

使用正确的测试用例进行编辑。 getData()返回SOME_STRING。但connect()返回null。那是我的问题。 – BudsNanKis

+0

编辑我的答案。 –

+0

那也是如此,问题在于mockHttpClient。由于某些原因,它无法自动嘲笑它。解决的办法是通过一些方法将httpclient作为参数传递(在我的情况下是构造函数) – BudsNanKis