Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito. Verify method param to be a particular class

I have a method:

void putObject(<T extends BaseEntity> param) 

Have some test where I mock this method, but I wonder, how to verify that method was called with parameter of particular class? Tried to do it in such ways:

verify(foo).putObject((SomeClass)anyObject()); ------ verify(foo).putObject(any(SomeClass.class)); ------ ArgumentCaptor<SomeClass> parameter = ArgumentCaptor             .forClass(SomeClass.class); verify(foo).putObject(parametr); 

Works only the second variant with any(), but it doesnt check class ofparameter`. So if it is possible to verify that method get any object of particular class?

like image 875
sphinks Avatar asked Feb 08 '13 12:02

sphinks


People also ask

How do you verify a method called in Mockito?

Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.

What does verify in Mockito do?

Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: ? 1. verify(mockObject).


2 Answers

User Matcher documentation isA() method.

public static <T> T isA(java.lang.Class<T> clazz)

That will solve your problem.

verify(foo).putObject(isA(SomeClass.class));

like image 109
TheWhiteRabbit Avatar answered Sep 22 '22 10:09

TheWhiteRabbit


Actually you can check with ArgumentCaptor.

ArgumentCaptor<SomeClass> parameterCaptor = ArgumentCaptor             .forClass(SomeClass.class); verify(foo).putObject(parameterCaptor.capture());  SomeClass instance = parameterCaptor.getValue(); // check intance.getX() // check instance.getY() 
like image 42
utkusonmez Avatar answered Sep 22 '22 10:09

utkusonmez