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(); } }
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With