java - 调用同一个mock方法时如何返回不同的结果?

标签 java unit-testing mockito

我有一个方法,我调用它连接到另一个服务器,每次调用它时,它都会返回不同的数据。
我正在为调用该方法的类编写单元测试。我 mock 了那个类,我希望它返回 stub 结果。它实际上可以使用 doReturn 来工作。 ,但每次都会返回相同的数据。我希望它返回不同的数据,并且我希望能够指定它应该是什么。

我尝试使用“doReturn - when”并且它有效,但我无法让它返回不同的结果。我不知道该怎么做。

我还尝试使用“when - thenReturn”,这是我在 StackOverflow 上找到的解决方案。这样,我可以指定每次调用相同的方法时得到不同的响应。

问题是我收到编译错误

The method XXX is undefined for the type OngoingStubbing<MyClass>

JSONArray jsonArray1 = { json array1 here };
JSONArray jsonArray2 = { json array2 here };

// Works but return the same jsonArray1 every time:
MyClass MyClassMock = mock(MyClass.class);
Mockito.doReturn(jsonArray1)
        .when(MyClassMock).getMyValues(any(List.class), any   (String.class), any(String.class),
                any(String.class),
                any(String.class));

// Does not work:
when(MyClassMock).getMyValues(any(List.class),
       any(String.class), any(String.class),
       any(String.class),
       any(String.class)).thenReturn(jsonArray1, jsonArray2);


// Compile error:
// The method getMyValues(any(List.class), any(String.class), any (String.class), any(String.class), any(String.class)) is undefined for the type OngoingStubbing<MyClass>

我得到编译错误:

The method getMyValues(any(List.class), any(String.class), any(String.class), any(String.class), any(String.class)) is undefined for the type OngoingStubbing

最佳答案

对于普通模拟,您可以使用如下内容:

when(mockFoo.someMethod())
            .thenReturn(obj1, obj2)
            .thenThrow(new RuntimeException("Fail"));

如果您使用spy() 和doReturn() 而不是when() 方法:

您需要在不同的调用上返回不同的对象是这样的:

doReturn(obj1).doReturn(obj2).when(this.client).someMethod();

关于java - 调用同一个mock方法时如何返回不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56460375/

相关文章:

android - 通过 Dagger Provide 模拟 AccountManager 时出现 Java.lang.reflect.InvocationTargetException。怎么修?

java - Java中使用Mockito模拟MongoDB的DeleteResult

java - Hadoop中的getJobStatus错误

Java IO 用于类路径上或类路径外的文件

java - Swing的KeyListener和同时按下的多个键

c# - 如何使用最小起订量来验证是否将类似的对象作为参数传入?

java - paintComponent 方法在 JLabel 上不显示任何内容?

javascript - 复用 mocha 测试代码

ios - @testable import "projectName"没有将所有文件导入测试用例

java - 测试使用同一类中的另一个方法的方法