39

In Mockito, is there a way to verify that there are no more interactions on any mock I have created?

For example:

public void test()
{
  ...
  TestObject obj = mock(TestObject);
  myClass.test();
  verifyNoMoreInteractionsWithMocks();  <-------
}

Is there such a method?

Nick Grealy
  • 24,216
  • 9
  • 104
  • 119
sworded
  • 2,419
  • 4
  • 31
  • 48
  • See http://stackoverflow.com/questions/512254/use-mockito-to-verify-that-nothing-is-called-after-a-method – Vadzim Oct 17 '13 at 10:33

1 Answers1

49

Since verifyNoMoreInteractions take an array of object we have to find a way to get all the created mocks.

You can create this class

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

and then use it in your test :

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

or with annotations :

@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
    }
}

It works but it adds a dependency on mockito internal.

kingston
  • 11,053
  • 14
  • 62
  • 116
gontard
  • 28,720
  • 11
  • 94
  • 117
  • 1
    This work great. The only problem is that when you use the @Mock annotation, it is not collected in the MocksCollector. – sworded Aug 20 '12 at 14:10
  • 2
    It looks like only @RunWith(PowerMockRunner.class) fails, while @RunWith(MockitoJUnitRunner.class) works fine. – sworded Aug 20 '12 at 14:36