Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

Here's the 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();

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...