Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito Disregard Parameters

Is there a way to get a mocked class to return some object no matter what arguments the function is called with?

For example, if one of my parameters' types did not have the .equals() method properly implemented.

like image 201
Jack Edmonds Avatar asked Jun 22 '11 01:06

Jack Edmonds


People also ask

When to use argument matchers in Mockito?

Argument matchers are mainly used for performing flexible verification and stubbing in Mockito. It extends ArgumentMatchers class to access all the matcher functions. Mockito uses equal() as a legacy method for verification and matching of argument values.

How do you verify a method called in Mockito?

Mockito verify() simple example It's the same as calling with times(1) argument with verify method. verify(mockList, times(1)). size(); If we want to make sure a method is called but we don't care about the argument, then we can use ArgumentMatchers with verify method.


2 Answers

when(mock.someMethod(any()).thenReturn(yourValue);

The any() matcher basically says you can have any value or a null. Check out the documentation at mockito, especially the section on Argument Matchers.

like image 187
drekka Avatar answered Oct 06 '22 00:10

drekka


There are also generics i.e.

when(mock.someMethod(Matchers.<String>any(), Matchers.<Interval>any(), Matchers.Integer>any())).thenReturn(yourValue);
like image 20
Yoztastic Avatar answered Oct 06 '22 00:10

Yoztastic