java 如何在对模拟的不同调用中返回不同的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32430387/
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
How do I return different values on different calls to a mock?
提问by user2032118
I have the following code which is getting the current counter value from DB. Then it updates the counter in DB and then again it retrieves the value.
我有以下代码从 DB 获取当前计数器值。然后它更新数据库中的计数器,然后再次检索该值。
int current = DBUtil.getCurrentCount();
DBUtil.updateCount(50);// it updates the current count by adding 50
int latest = DBUtil.getCurrentCount();
I want to mock the static methods in such a way that the first call should return 100 and the second call should return 150. How can I use PowerMockito to achieve this? I am using TestNG, Mockito along with PowerMock.
我想以这样一种方式模拟静态方法,即第一次调用应返回 100,第二次调用应返回 150。如何使用 PowerMockito 来实现这一点?我正在使用 TestNG、Mockito 和 PowerMock。
回答by durron597
Mockito supports changing the returned value; this support extends to PowerMockito. Just use OngoingStubbing.thenReturn(T value, T... values)
Mockito 支持改变返回值;这种支持扩展到 PowerMockito。只需使用OngoingStubbing.thenReturn(T value, T... values)
OngoingStubbing<T> thenReturn(T value, T... values)
Sets consecutive return values to be returned when the method is called.
E.g:when(mock.someMethod()).thenReturn(1, 2, 3);
Last return value in the sequence (in example: 3) determines the behavior of further consecutive calls.
OngoingStubbing<T> thenReturn(T value, T... values)
设置调用方法时要返回的连续返回值。
例如:when(mock.someMethod()).thenReturn(1, 2, 3);
序列中的最后一个返回值(在示例中:3)决定了后续连续调用的行为。
So, in this case, you would do:
所以,在这种情况下,你会这样做:
PowerMockito.when(DBUtil.getCurrentCount()).thenReturn(100, 150);
Note: this answer assumes you already know how to mock static
methods. If you do not, see this question.
注意:这个答案假设您已经知道如何模拟static
方法。如果没有,请参阅此问题。