我正在尝试使用Mockito MockedStatic来模拟静态方法。
我在Spring Boot和maven中使用mockito-core和mockito-inline版本3.6.0。
我不能设法让模拟工作,我在Unirest::post上有一个“无法解析方法post”,你可以在下面的代码中看到:
@Test
public void test() {
try (MockedStatic<Unirest> mock = Mockito.mockStatic(Unirest.class)) {
mock.when(Unirest::post).thenReturn(new HttpRequestWithBody(HttpMethod.POST, "url"));
}
}Unirest类来自unirest-java包。
是否有人已经遇到了这个问题并有解决方案?
发布于 2020-11-13 16:27:20
方法Unirest.post(String url)接受一个参数,因此不能使用Unirest::post引用它。
您可以使用以下内容:
@Test
void testRequest() {
try (MockedStatic<Unirest> mockedStatic = Mockito.mockStatic(Unirest.class)) {
mockedStatic.when(() -> Unirest.post(ArgumentMatchers.anyString())).thenReturn(...);
someService.doRequest();
}
}但请记住,您现在必须模拟整个Unirest使用情况以及它上的每个方法调用,因为默认情况下模拟会返回null。
如果你想测试你的超文本传输协议客户端,看看WireMock或者来自OkHttp的MockWebServer。通过这种方式,您可以使用真实的HTTP通信来测试您的客户端,并且还可以测试诸如响应缓慢或5xx HTTP代码之类的极端情况。
https://stackoverflow.com/questions/64785793
复制相似问题