java mockito 在 spy 方法上返回对象序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17714291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:45:44  来源:igfitidea点击:

mockito return sequence of objects on spy method

javamockito

提问by David

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()像下面这样的间谍

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?

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

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

我有一个像下面这样的课程,我正在尝试测试它。我想测试myClass,不是anotherClass

public class myClass{

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

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

回答by fge

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

您可以doReturn()在之前链接调用when(),所以这有效(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,z2),当我必须这样做时,我也使用链式.thenReturn()调用:

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