【问题标题】:Mockito MockedStatic when() "Cannot resolve method"Mockito MockedStatic when()“无法解析方法”
【发布时间】:2026-02-10 06:25:02
【问题描述】:

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

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

我无法使模拟工作,我在Unirest::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 包。

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

【问题讨论】:

标签: spring-boot mocking mockito


【解决方案1】:

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

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

【讨论】:

  • 谢谢,它有效!不过,正如你所提议的,我使用 MockServer 来断言生成的请求