New method for loading all mocks in test

131 views
Skip to first unread message

Stan Tarasov

unread,
May 23, 2022, 1:43:30 PM5/23/22
to mockito
Hello,

We use Mockito in our projects a lot and lately I've been having an idea about adding a method that allows to get all mocks for a test method. Looks something like this:

@ExtendWith(MockitoExtension.class)
class TestClass {

        @Mock
        Object mock1;

        Object mock2;

        @BeforeEach
        void init() { 
                mock2 = mock(Object.class);
        }

        @Test
        void compareFailTest() {
        //setup  
        Object mock3 = mock(Object.class);

        //run
        //...

        //verify
        //...

        Object[] mocks = Mockito.getCurrentMocks(); //[mock1, mock2, mock3]
        Mockito.verifyNoMoreInteractions(mocks);
     }
}

Getting all of the mocks and then checking them with verifyNoMoreInteractions for example will allow for more strict tests and thus to catch subtle changes in behavior leading to less bugs.   There is a listener half-solution here https://stackoverflow.com/questions/48184291/mockito-get-all-mocked-objects  but it doesn't cover the case with @Mock and MockitoExtension.

I would be happy to participate in the implementation.

Sorry if this has already been brought up by someone and rejected - tried to find a conversation on the topic and did not.

Thanks! 
Reply all
Reply to author
Forward
0 new messages