Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito get all mocked objects

I want to get the list of all mocked objects. Using a previous version of Mockito I could do this:

List<Object> createdMocks = new LinkedList<Object>();
MockingProgress progress = new ThreadSafeMockingProgress();
progress.setListener(new CollectCreatedMocks(createdMocks));

These listeners are removed in the latest 2.8 version of Mockito, is there any alternative for it?

like image 619
user3813133 Avatar asked Aug 11 '26 00:08

user3813133


1 Answers

Since Mockito 2.x this has been replaced by implementations of org.mockito.listeners.MockitoListener which you engage like so:

Mockito.framework().addListener()

For example:

@Test
public void listAllMocks() {
    List<Object> mocks = new ArrayList<>();

    // can be replaced by a lambda if using java 8+
    Mockito.framework().addListener(new MockCreationListener() {
        @Override
        public void onMockCreated(Object mock, MockCreationSettings settings) {
            mocks.add(mock);
        }
    });

    A a = Mockito.mock(A.class);
    B b = Mockito.mock(B.class);

    // ... do something with a, b

    // verify
    assertThat(mocks.size(), is(2));
    assertThat(mocks, hasItem(a));
    assertThat(mocks, hasItem(b));
}
like image 132
glytching Avatar answered Aug 12 '26 13:08

glytching