Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting method invocations in Unit tests

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

like image 981
user855 Avatar asked Oct 08 '11 05:10

user855


People also ask

How do you unit test methods?

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.

Do you need a unit test for every method?

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.

How do you run the same test case multiple times in Junit?

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.

What is the use of verify in Mockito?

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.


2 Answers

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

like image 189
case nelson Avatar answered Oct 20 '22 13:10

case nelson


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(); 
like image 36
Jakub Kubrynski Avatar answered Oct 20 '22 11:10

Jakub Kubrynski