gpt4 book ai didi

java - PowerMockito.when 返回 null

转载 作者:行者123 更新时间:2023-11-30 08:32:39 24 4
gpt4 key购买 nike

我不确定为什么 PowerMockito.when 返回 null。这是我正在测试的类(class):

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 行:

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

谁能帮帮我?

最佳答案

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

解决这个问题的方法是使用 Matchers.eq()当你模拟时,这样 when 将在每个对象上执行等于你传递的对象:

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

关于java - PowerMockito.when 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40038233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com