I tried out the mock-maker-inline "Incubation" feature of Mockito to be able to mock a final class (problem described and discussed here). Since then other tests fail with:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();
when I define an exception to be thrown by a spy. Relevant code from one of the tests:
In @Configuration class:
@Bean
public MessagePersister messagePersister() {
return Mockito.spy(new MessagePersister(...));
}
Note: MessagePersister is proxied by CGLIB.
In Test class:
@Inject
private MessagePersister messagePersisterSpy;
@Test
public void exceptionInPersisterTest() {
doThrow(new SomeException("exceptionFromTest")).doCallRealMethod()
.when(messagePersisterSpy).persistMessages(any());
...
}
The exception is understandable. The class of messagePersisterSpy is MessagePersister$$EnhancerBySpringCGLIB$$6c49f1e2, but if I remove the mock-maker-inline feature, my spy is of class MessagePersister$MockitoMock$515952708$$EnhancerBySpringCGLIB$$9523b504 and the tests are green.
Any ideas where this interference comes from and if I can do something about it ?
Thank you !
Found the solution after a lot of digging: specify the mock maker explicitly for the classes that are not getting mocked as expected.
// using annotation
@Mock(mockMaker = MockMakers.SUBCLASS)
Foo mock;
// using MockSettings.withSettings()
Foo mock = Mockito.mock(Foo.class, withSettings().mockMaker(MockMakers.SUBCLASS));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With