Counting method invocations in Unit tests

user855 picture user855 · Oct 8, 2011 · Viewed 72.6k times · Source

What is the best way to count method invocations in a Unit Test. Do any of the testing frameworks allow that?

Answer

case nelson picture case nelson · Oct 8, 2011

It sounds like you may want to be using the .expects(1) type methods that mock frameworks usually provide.

Using mockito, if you were testing a List and wanted to verify that clear was called 3 times and add was called at least once with these parameters you do the following:

List mock = mock(List.class);        
someCodeThatInteractsWithMock();                 

verify(mock, times(3)).clear();
verify(mock, atLeastOnce()).add(anyObject());      

Source - MockitoVsEasyMock