Mockito MockedStatic when() "Cannot resolve method"

Mockito MockedStatic when() "Cannot resolve method"

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

我正在使用 mockito-core 和 mockito-inline 版本 3.6.0 Spring Boot 和 maven。

我无法使模拟工作,我在 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 class 来自 unirest-java 包。

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

方法 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 用法以及默认情况下对它的每个方法调用作为模拟 returns null

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