Search code examples
javaunit-testingmockitopowermockito

mockito Powermockito object mapper


I am using the following to mock writeValueAsString(any()) method in the object mapper. However the writeValueAsString method is not getting mocked and getting called in the method I am testing in the application.

I did try spy as well but it did not work. Is there any other suggestion.

Trial 1

ObjectMapper mockOM = Mockito.mock(ObjectMapper.class);
when(mockOM.writeValueAsString(any())).thenReturn(t);

Trial 2

ObjectMapper mockOM = Mockito.spy(new ObjectMapper());
when(mockOM.writeValueAsString(any())).thenReturn(t);

t is a string here.

Any help will be great


Solution

  • I've ran into the same issue once. The following solved it for me:

    ObjectMapper mockOM = Mockito.mock(ObjectMapper.class);
    // old: when(mockOM.writeValueAsString(any())).thenReturn(t);
    doReturn(t).when(mockOM).writeValueAsString(any());