Mockito MockedStatic when()“无法解析方法”

Ybr*_*bri 2 mocking mockito spring-boot

我正在尝试使用 Mockito MockedStatic 来模拟静态方法。

我将mockito-core和mockito-inline版本3.6.0与Spring Boot和maven一起使用。

我无法使模拟工作,我有一个“无法解析方法帖子”,Unirest::post您可以在下面的代码中看到:

@Test
public void test() {
    try (MockedStatic<Unirest> mock = Mockito.mockStatic(Unirest.class)) {
        mock.when(Unirest::post).thenReturn(new HttpRequestWithBody(HttpMethod.POST, "url"));
    }
}
Run Code Online (Sandbox Code Playgroud)

Unirest 类来自unirest-java包。

有人遇到过这个问题并有解决方案吗?

rie*_*pil 8

该方法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();
  }
}
Run Code Online (Sandbox Code Playgroud)

但请记住,您现在必须模拟整个Unirest用法和每个方法调用,因为模拟null默认返回。

如果您想测试您的 HTTP 客户端,请查看WireMock或OkHttp 中的MockWebServer。通过这种方式,您可以使用真实的 HTTP 通信来测试客户端,并且还可以测试诸如缓慢响应或 5xx HTTP 代码之类的极端情况。