Mockito获得所有模拟对象

时间:2018-01-10 09:36:47

标签: java unit-testing testing mocking mockito

我想获取所有模拟对象的列表。使用以前版本的Mockito,我可以这样做:

!important

这些听众在最新的2.8版Mockito中删除了,还有其他选择吗?

1 个答案:

答案 0 :(得分:3)

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