Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito return sequence of objects on spy method

Tags:

java

mockito

I know you can set several different objects to be be returned on a mock. Ex.

when(someObject.getObject()).thenReturn(object1,object2,object3); 

Can you do the same thing with a spied object somehow? I tried the above on a spy with no luck. I read in the docs to use doReturn() on a spy like below

doReturn("foo").when(spy).get(0); 

But deReturn() only accepts one parameter. I'd like to return different objects in a specific order on a spy. Is this possible?

I have a class like the following and i'm trying to test it. I want to test myClass, not anotherClass

public class myClass{      //class code that needs several instances of `anotherClass`      public anotherClass getObject(){         return new anotherClass();     } } 
like image 212
David Avatar asked Jul 18 '13 04:07

David


People also ask

What is the difference between spy and mock in Mockito?

Mocks are used to create fully mock or dummy objects. It is mainly used in large test suites. Spies are used for creating partial or half mock objects. Like mock, spies are also used in large test suites.

How does Mockito spy work?

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.

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.


1 Answers

You can chain doReturn() calls before when(), so this works (mockito 1.9.5):

private static class Meh {     public String meh() { return "meh"; } }  @Test public void testMeh() {     final Meh meh = spy(new Meh());      doReturn("foo").doReturn("bar").doCallRealMethod().when(meh).meh();      assertEquals("foo", meh.meh());     assertEquals("bar", meh.meh());     assertEquals("meh", meh.meh()); } 

Also, I didn't know you could do when(x.y()).thenReturn(z1,z2), when I have to do this I use chained .thenReturn() calls as well:

when(x.y()).thenReturn(z1).thenThrow().thenReturn(z2) 
like image 154
fge Avatar answered Sep 24 '22 16:09

fge