PowerMockito.doReturn returns null

試著忘記壹切 提交于 2019-12-02 10:36:46

Instead of

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

you should use

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

You also have some problems in your test : incorrect mocking constructor and you don't need httpResponse at all.

Update This code works correctly to me:

@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());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!