PowerMockito.doReturn returns null



这是我正在测试的类:

public class A {
public Integer callMethod(){
  return someMethod();
}

private Integer someMethod(){
  //Some Code
  HttpPost httpPost = new HttpPost(oAuthMessage.URL);
  //Some Code
  HttpClient httpClient = new DefaultHttpClient();
  HttpResponse httpResponse = httpClient.execute(httpPost); ------1
  Integer code = httpResponse.getStatusLine().getStatusCode(); ---2
  return code;
}

现在我想模拟第1行&2&返回一个mock HttpResponse&密码

我尝试过,但失败了:

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.crypto.*")
public class TestA {
//Spying some things here & Injecting them
@Test
public void testA() {

   DefaultHttpClient defaultHttpClientMock = PowerMockito.mock(DefaultHttpClient.class);
   HttpResponse httpResponse = PowerMockito.mock(HttpResponse.class, RETURNS_DEEP_STUBS);
   HttpClient httpClient = PowerMockito.mock(HttpClient.class);
   //HttpResponse httpResponseMock    PowerMockito.mock(HttpResponse.class);
   HttpPost httpPost = PowerMockito.mock(HttpPost.class);
   PowerMockito.whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(defaultHttpClientMock);
   PowerMockito.doReturn(httpResponse).when(httpClient).execute(httpPost);      //Returns null. It never returns httpResponse.
   PowerMockito.when(httpResponse.getStatusLine().getStatusCode()).thenReturn(anyInt());
   //call the method
}

PowerMockito.doReturn(httpResponse).when(httpClient).execute(httpPost)总是返回null。我希望它返回HttpResponse的mock对象。我已经阅读了与这个错误相关的其他帖子,但不确定在我的情况下该怎么办。有人能帮忙吗?

而不是

PowerMockito.doReturn(httpResponse).when(httpClient).execute(httpPost);

你应该使用

PowerMockito.when(httpResponse.execute(httpPost)).thenReturn(httpResponse);

测试中也有一些问题:mocking构造函数不正确,根本不需要httpResponse。

更新这段代码对我来说是正确的:

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.crypto.*")
@PrepareForTest({ HttpPost.class, DefaultHttpClient.class, A.class })
public class TestA {
    @Test
    public void testA() throws Exception {
        HttpPost httpPost = Mockito.mock(HttpPost.class);
        PowerMockito.whenNew(HttpPost.class).withArguments(oAuthMessage.URL).thenReturn(httpPost);
        DefaultHttpClient defaultHttpClientMock = PowerMockito.mock(DefaultHttpClient.class);
        HttpResponse httpResponse = PowerMockito.mock(HttpResponse.class);
        PowerMockito.whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(defaultHttpClientMock);
        PowerMockito.when(defaultHttpClientMock.execute(httpPost)).thenReturn(httpResponse);
        StatusLine statusLine = PowerMockito.mock(StatusLine.class);
        PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);
        Integer expected = new Integer(0);
        PowerMockito.when(statusLine.getStatusCode()).thenReturn(expected);
        A a = new A();
        Assert.assertEquals(expected, a.callMethod());
    }
}

相关内容

  • 没有找到相关文章

最新更新