What is the best way to count method invocations in a Unit Test. Do any of the testing frameworks allow that?
A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.
Every behavior should be covered by a unit test, but every method doesn't need its own unit test. Many developers don't test get and set methods, because a method that does nothing but get or set an attribute value is so simple that it is considered immune to failure.
The easiest (as in least amount of new code required) way to do this is to run the test as a parametrized test (annotate with an @RunWith(Parameterized. class) and add a method to provide 10 empty parameters). That way the framework will run the test 10 times.
Mockito Verify methods are used to check that certain behavior happened. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called.
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
In Mockito you can do something like this:
YourService serviceMock = Mockito.mock(YourService.class); // code using YourService // details of all invocations including methods and arguments Collection<Invocation> invocations = Mockito.mockingDetails(serviceMock).getInvocations(); // just a number of calls of any mock's methods int numberOfCalls = invocations.size();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With