我想获取所有模拟对象的列表。使用以前版本的Mockito,我可以这样做:
List<Object> createdMocks = new LinkedList<Object>();
MockingProgress progress = new ThreadSafeMockingProgress();
progress.setListener(new CollectCreatedMocks(createdMocks));
这些侦听器在最新的 Mockito 2.8 版本中被删除,还有其他选择吗?
从 Mockito 2.x 开始,这已被您参与的org.mockito.listeners.MockitoListener
的实现所取代,如下所示:
Mockito.framework().addListener()
例如:
@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));
}