Using argument matchers for stubbing
Before going into detail regarding the different ways of stubbing method calls, we have to define the concept of argument matchers. When passing arguments to the mock's methods during the stubbing process, Mockito verifies argument values using the equals()
method. In other words, when calling the following code:
Person smith = new Person(); given(taxFactorFetcher.getTaxFactorFor(smith).willReturn(10);
Mockito will check whether the person passed as an argument to the getTaxFactorFor(...)
method equals to our person (in this case, Mr. Smith). If that is the case, only then will Mockito return 10
as the output of the getTaxFactorFor(...)
method.
There are cases where you want to perform more complex verification of the passed argument. Mockito already gives you quite a few predefined argument matchers and also provides you with the integration with Hamcrest to create custom argument matchers (check Chapter 7, Verifying Behavior with Object Matchers, for more...