在Mockito中,有没有办法验证我创建的任何模拟器上没有更多的交互?
例如:
public void test()
{
...
TestObject obj = mock(TestObject);
myClass.test();
verifyNoMoreInteractionsWithMocks(); <-------
}
有这样的方法吗?
答案 0 :(得分:32)
由于verifyNoMoreInteractions采用了一个对象数组,我们必须找到一种方法来获取所有创建的模拟。
您可以创建此课程
public class MocksCollector {
private final List<Object> createdMocks;
public MocksCollector() {
createdMocks = new LinkedList<Object>();
final MockingProgress progress = new ThreadSafeMockingProgress();
progress.setListener(new CollectCreatedMocks(createdMocks));
}
public Object[] getMocks() {
return createdMocks.toArray();
}
}
然后在测试中使用它:
public class ATest {
private final MocksCollector mocksCollector = new MocksCollector();
@Test
public void test() throws Exception {
A a1 = mock(A.class);
A a2 = mock(A.class);
A a3 = mock(A.class);
assertEquals("wrong amount of mocks", 3, mocksCollector.getMocks().length);
verifyNoMoreInteractions(mocksCollector.getMocks());
a3.doSomething();
verifyNoMoreInteractions(mocksCollector.getMocks()); // fail
}
}
或带注释:
@RunWith(MockitoJUnitRunner.class)
public class A2Test {
private final MocksCollector mocksCollector = new MocksCollector();
@Mock
private A a1;
@Mock
private A a2;
@Mock
private A a3;
@Test
public void test() throws Exception {
assertEquals("wrong amount of mocks", 3, mocksCollector.getMocks().length);
verifyNoMoreInteractions(mocksCollector.getMocks());
a2.doSomething();
verifyNoMoreInteractions(mocksCollector.getMocks()); // fail
}
}
它有效,但它增加了对mockito内部的依赖。