我正尝试在我的spring boot应用程序中使用okhttp和Mockito,但我总是得到NullPointerException的提示
HttpClient.newCall(请求).execute()
我们如何在okhttp中使用Mockito?
@Component
public class HStatus {
@Autowired
private OkHttpClient httpClient;
public int HCheck() throws URISyntaxException, IOException {
String url = new URIBuilder("Some URL").build().toString();
Request request = new Request.Builder().url(url).get().build();
try (Response resp = httpClient.newCall(request).execute()) {
return resp.code();
}
}
在junit中,我正在尝试做-
@RunWith(MockitoJUnitRunner.class)
public class HStatusTest {
@InjectMocks
private HStatus hStatus;
@Mock
private OkHttpClient httpClient;
@Test
public void TestHCheck_Should_Return_200_StatusCode() throws URISyntaxException, IOException {
Response resp = new Response.Builder()
.request(new Request.Builder().url("SOME URL").build())
.protocol(Protocol.HTTP_1_1)
.code(200).message("")
.build();
Mockito.when(httpClient.newCall(ArgumentMatchers.any()).execute).thenReturn(resp);
// Getting NullPointer at this call -> httpClient.newCall(ArgumentMatchers.any()).execute
int statusCode = hStatus.HCheck();
assertEquals(200, statusCode);
}
}
发布于 2021-10-14 14:38:16
我猜您正在创建OkHttpClient的新实例。
对于创建新的实例,不容易用mockito来模仿它们。您可以使用mockito @Spy,但我不喜欢这样做。
否则,您可以使用powermock
OkHttpClient mockClient = mock(OkHttpClient.class);
PowerMockito.whenNew(OkHttpClient.class).withNoArguments().thenReturn(mockClient);
另一种方法:为新的OkHttpClient();创建一个getter类并模拟它。
getClient(){
return new OkHttpClient();
}
在mockito中
when(class.getClient()).thenReturn(mockClient);
https://stackoverflow.com/questions/69572392
复制相似问题