首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerMockito.when返回空

PowerMockito.when返回空
EN

Stack Overflow用户
提问于 2016-10-14 08:14:24
回答 1查看 3.2K关注 0票数 6

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

代码语言:javascript
复制
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
}

在第1行中,我将httpResponse作为null。我想得到一个模拟的HTTPResponse对象,这样我就可以继续下去了。

我也尝试过这样做,而不是第3行:

代码语言:javascript
复制
CloseableHttpResponse closeableHttpResponse = PowerMockito.mock(CloseableHttpResponse.class);
PowerMockito.when(closeableHttpClientMock.execute(httpPost)).thenReturn(closeableHttpResponse);

有谁可以帮我?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-14 08:26:30

问题似乎在于,您在模拟时传递的httpPost实例与在执行过程中传递的实例不同。

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

代码语言:javascript
复制
PowerMockito.when(httpClientMock.execute(Matchers.eq(httpPost)))
  .thenReturn(httpResponseMock);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40038233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档