Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: Trying to spy on method is calling the original method

I'm using Mockito 1.9.0. I want mock the behaviour for a single method of a class in a JUnit test, so I have

final MyClass myClassSpy = Mockito.spy(myInstance); Mockito.when(myClassSpy.method1()).thenReturn(myResults); 

The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception. The only reason I'm using mocks is so that later, whenever myClassSpy.method1() is called, the real method won't be called and the myResults object will be returned.

MyClass is an interface and myInstance is an implementation of that, if that matters.

What do I need to do to correct this spying behaviour?

like image 642
Dave Avatar asked Jul 23 '12 20:07

Dave


People also ask

Does Mockito spy call real method?

A mock does not call the real method, it is just proxy for actual implementations and used to track interactions with it. A spy is a partial mock, that calls the real methods unless the method is explicitly stubbed. Since Mockito does not mock final methods, so stubbing a final method for spying will not help.

How do you mock a 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.

What is the difference between spy and mock in Mockito?

Both can be used to mock methods or fields. The difference is that in mock, you are creating a complete mock or fake object while in spy, there is the real object and you just spying or stubbing specific methods of it. When using mock objects, the default behavior of the method when not stub is do nothing.

When should we use spy in Mockito?

Simply put, the API is Mockito. spy() to spy on a real object. This will allow us to call all the normal methods of the object while still tracking every interaction, just as we would with a mock. Note how the real method add() is actually called, and how the size of spyList becomes 2.


2 Answers

Let me quote the official documentation:

Important gotcha on spying real objects!

Sometimes it's impossible to use when(Object) for stubbing spies. Example:

List list = new LinkedList(); List spy = spy(list);  // Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo");  // You have to use doReturn() for stubbing doReturn("foo").when(spy).get(0); 

In your case it goes something like:

doReturn(resultsIWant).when(myClassSpy).method1(); 
like image 91
Tomasz Nurkiewicz Avatar answered Oct 09 '22 23:10

Tomasz Nurkiewicz


In my case, using Mockito 2.0, I had to change all the any() parameters to nullable() in order to stub the real call.

like image 39
ejaenv Avatar answered Oct 09 '22 22:10

ejaenv