PowerMockito.doReturn returns null

后端 未结 1 815
深忆病人
深忆病人 2021-01-25 15:56

This is my class under test:

public class A {

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


private Integer someMethod(){
  //Some Code
  HttpPost htt         


        
相关标签:
1条回答
  • 2021-01-25 16:50

    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题