问题
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