我有一个方法,我调用它连接到另一个服务器,每次调用它时,它都会返回不同的数据。
我正在为调用该方法的类编写单元测试。我 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/