Ken Y-N Ken Y-N - 3 months ago 9
Java Question

Getting number of calls to a mock

Assume I want to test code like this:

class ClassToTest
// UsedClass1 contains a method UsedClass2 thisMethod() {}
UsedClass1 foo;
void aMethod()
{
int max = new Random().nextInt(100);
for(i = 0; i < max; i++)
{
foo.thisMethod().thatMethod();
}
}
}


If I have a test like this:

ClassToTest test;
UsedClass1 uc1;
UsedClass2 uc2;
@Test
public void thingToTest() {
test = new ClassToTest();
uc1 = mock(UsedClass1.class);
uc2 = mock(UsedClass2.class);
when(uc1.thisMethod()).thenReturn(uc2);
when(uc2.thatMethod()).thenReturn(true);

test.aMethod();

// I would like to do this
verifyEquals(callsTo(uc1.thisMethod()), callsTo(uc2.thatMethod()));
}


How can I get the number of calls to
uc1.thisMethod()
and
uc2.thatMethod()
so I can check they were both called the same number of times?

Answer

You could stub your methods, and increment a counter, like this:

final AtomicInteger countCall1 = new AtomicInteger();

Mockito.doAnswer(new Answer<UsedClass2>() {
    @Override
    public UsedClass2 answer(InvocationOnMock invocation) throws Throwable {
        countCall1.incrementAndGet();
        return uc2;
    }
}).when(uc1).thisMethod();