PowerMockito.doReturn returns null
这是我正在测试的课程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 行
代替
你应该使用
1 | PowerMockito.when(httpResponse.execute(httpPost)).thenReturn(httpResponse); |
你的测试也有一些问题:不正确的模拟构造函数,你根本不需要 httpResponse。
更新此代码对我来说可以正常工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | @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()); } } |