Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock-maker-inline makes other mocks not work

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 !

like image 893
Tchypp Avatar asked Jun 01 '26 08:06

Tchypp


1 Answers

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));
like image 134
user3416827 Avatar answered Jun 02 '26 20:06

user3416827