PowerMockito.when returns null



我不知道为什么PowerMockito.when返回null。这是我要测试的类:

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

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


@RunWith(PowerMockRunner.class)
@PrepareForTest({ MacmillanServiceImpl.class, PersonService.class, AuthorizeServiceImpl.class, ProvisionHelper.class, ESPHelper.class,
        DPFServiceImpl.class, TransactionLogServiceImpl.class, HttpClient.class, HttpEntity.class, InputStream.class, IOUtils.class,
        DTOUtils.class, MacmillanESPResponseDTO.class, HttpClientBuilder.class, CloseableHttpClient.class, HttpPost.class, IOUtils.class,
        HttpResponse.class, CloseableHttpResponse.class, StatusLine.class })
@PowerMockIgnore({ "javax.crypto.*", "javax.net.ssl.*" })
public class TestA {
//Spying some things here & Injecting them
@Test
public void testA() {

HttpClient httpClientMock = PowerMockito.mock(HttpClient.class);
HttpClientBuilder httpClientBuilderMock = PowerMockito.mock(HttpClientBuilder.class);
CloseableHttpClient closeableHttpClientMock = PowerMockito.mock(CloseableHttpClient.class);
HttpResponse httpResponseMock = PowerMockito.mock(HttpResponse.class);
PowerMockito.mockStatic(HttpClientBuilder.class);
given(HttpClientBuilder.create()).willReturn(httpClientBuilderMock);
when(httpClientBuilderMock.build()).thenReturn(closeableHttpClientMock);
PowerMockito.when(httpClientMock.execute(httpPost)).thenReturn(httpResponseMock); --This does not work----Line 3
//Other codes
//call the method
}

在第一行中,我得到httpResponse为空。我想得到一个模拟的HTTPResponse对象,以便我可以进一步进行。

我也试过这样代替第3行:

CloseableHttpResponse closeableHttpResponse = PowerMockito.mock(CloseableHttpResponse.class);
PowerMockito.when(closeableHttpClientMock.execute(httpPost)).thenReturn(closeableHttpResponse);

有人能帮我吗?

似乎问题是您在mock时传递的httpPost实例与您在执行中传递的实例不一样。

要解决这个问题,你可以在模拟时使用Matchers.eq(),这样when将在每个与你传递的对象相等的对象上执行:

PowerMockito.when(httpClientMock.execute(Matchers.eq(httpPost)))
  .thenReturn(httpResponseMock);

相关内容

  • 没有找到相关文章

最新更新