How to write Mockito.when() for Json.mapper().constructType(type)

Viewed 24

Can anyone tell me how to mock and write Mockito.when() method for

@Override
public Property resolveProperty(Type type, ModelConverterContext context, Annotation[] annotations, Iterator<ModelConverter> chain) {
   JavaType jType = Json.mapper().constructType(type);
   ...
}

I wrote

when(Json.mapper()).thenReturn(objectMapper);
when(objectMapper.constructType(type)).thenReturn(jType);

I am getting below error

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example:

  when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:

  • you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified.
  • inside when() you don't call method on mock but on some other object.
  • the parent of the mocked class is not public. It is a limitation of the mock engine.
1 Answers

You're trying to mock a static method. This is discouraged, but if you still want to do that, you need to use Mockito's version 3.4.0 or higher mockStatic method (mockito-inline dependency should be used).

var objectMapper = mock(ObjectMapper.class);
when(objectMapper.constructType(type)).thenReturn(jType);
try (var mocked = mockStatic(Json.class)) {
    mocked.when(Json::mapper).thenReturn(objectMapper);
    // execute the tested code
 }

See multiple examples here.

Related