ArgumentMatcher

Match arguments passed in a method of your mock

Basic Rule to match any statement with Mockito is to correctly match its parameters. If any of the parameter did not match then instruction will not be mocked.

// example statement
final int addition = calculator.getAddition(2, 3);

// you have to match exact parameters, in this case (2,3)
Mockito.when(mckCalculator.getAddition(2, 3)).thenReturn(5);

// If you mock for (3,4), you mocked result will not be returned
Mockito.when(mckCalculator.getAddition(3, 4)).thenReturn(5);

// For cases, where you do not know exact parameter then you can use Mockito.anyInt()
Mockito.when(mckCalculator.getAddition(Mockito.anyInt(), Mockito.anyInt())).thenReturn(5);

Similarly we have Mockito.any(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyByte(), Mockito.anyChar(), Mockito.anyFloat(), Mockito.anyDouble(), Mockito.anyShort(), Mockito.anyList(), Mockito.anySet() and Mockito.anyMap()

Last updated