Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito MockedStatic when() "Cannot resolve method"

I am trying to use Mockito MockedStatic to mock a static method.

I am using mockito-core and mockito-inline version 3.6.0 with Spring Boot and maven.

I can't manage to make the mock work, I have a "Cannot resolve method post" on the Unirest::post that you can see in the code below:

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

The Unirest class comes from the unirest-java package.

Did someone encounter this issue already and have a solution?

like image 731
Ybri Avatar asked May 09 '26 00:05

Ybri


1 Answers

The method Unirest.post(String url) takes an argument and hence you can't refer to it using Unirest::post.

You can use the following:

@Test
void testRequest() {
  try (MockedStatic<Unirest> mockedStatic = Mockito.mockStatic(Unirest.class)) {
    mockedStatic.when(() -> Unirest.post(ArgumentMatchers.anyString())).thenReturn(...);
    someService.doRequest();
  }
}

But keep in mind that you have to mock now the whole Unirest usage and every method call on it as the mock returns null by default.

If you want to test your HTTP clients take a look at WireMock or the MockWebServer from OkHttp. This way you test your clients with real HTTP communication and can test also corner cases like slow responses or 5xx HTTP codes.

like image 105
rieckpil Avatar answered May 11 '26 14:05

rieckpil