Mockito get all mocked objects

强颜欢笑 提交于 2021-02-10 12:07:29

问题


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?


回答1:


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));
}


来源:https://stackoverflow.com/questions/48184291/mockito-get-all-mocked-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!