2013-07-18 102 views
21

我知道你可以设置几个不同的对象,以便在模拟上返回。防爆。mockito间谍方法返回对象的序列

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

你能以某种方式做一个窥探对象吗?我尝试了上面的一个间谍没有运气。我在阅读文档对间谍使用doReturn()像下面

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

deReturn()只接受一个参数。我想按照特定的顺序返回不同的对象。这可能吗?

我有一个类如下,我试图测试它。我想测试myClass,不anotherClass

public class myClass{ 

    //class code that needs several instances of `anotherClass` 

    public anotherClass getObject(){ 
     return new anotherClass(); 
    } 
} 

回答

28

你可以连续when()doReturn()调用,所以此工程(1.9.5的Mockito):

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()); 
} 

另外,我不知道你能做到when(x.y()).thenReturn(z1,z2),当我必须做到这一点我使用链式.thenReturn()电话,以及:

when(x.y()).thenReturn(z1).thenThrow().thenReturn(z2) 
+0

我只补充一点,我宁愿'BDDMockito'别名,但这是代码中的首选项。这将提供以下内容:'willReturn(“foo”)。willReturn(“bar”)。willCallRealMethod()。given(meh).meh();' – Brice