Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito verify the return of a spied object method

Tags:

java

mockito

I know you can verify the times a spied object's method was called. Can you verify the result of the method call?

Something like the following?

verify(spiedObject, didReturn(true)).doSomething();
like image 1000
David Avatar asked Jun 06 '13 16:06

David


People also ask

What is verify return 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.

How do you mock the spy method?

Mockito provides a method to partially mock an object, which is known as the spy method. When using the spy method, there exists a real object, and spies or stubs are created of that real object. If we don't stub a method using spy, it will call the real method behavior.

How verify method works in Mockito?

Mockito. verify() will just verify that an invocation was done on a mock during the method execution. It means that if the real implementation of the mocked class doesn't work as it should, the test is helpless. As a consequence, a class/method that you mock in a test have also to be unitary tested.

What is Mockito Spy ()?

A Mockito spy is a partial mock. We can mock a part of the object by stubbing few methods, while real method invocations will be used for the other. By saying so, we can conclude that calling a method on a spy will invoke the actual method, unless we explicitly stub the method, and therefore the term partial mock.


1 Answers

To verify the number of times it was invoked, use verify(spiedObject, times(x)).doSomething().

You should NOT be verifying the value returned from the spied object. It is not the object under test so why verify what it returns. Instead verify the behavior of the object under test in response to the value returned from the spy.

Also, if you don't KNOW what value will be returned by the spied object it would be better to use a mock instead of a spy.

like image 71
John B Avatar answered Sep 28 '22 05:09

John B