Monday, January 21, 2019

java - 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?


Answer



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(resulstIWant).when(myClassSpy).method1();

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...