如何在对模拟的不同调用中返回不同的值? [英] How do I return different values on different calls to a mock?
问题描述
我有以下代码从DB获取当前计数器值。然后它更新DB中的计数器,然后再次检索该值。
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.
int current = DBUtil.getCurrentCount();
DBUtil.updateCount(50);// it updates the current count by adding 50
int latest = DBUtil.getCurrentCount();
我想以第一次调用应返回100和第二次调用的方式模拟静态方法呼叫应返回150.如何使用PowerMockito实现此目的?我正在使用TestNG,Mockito和PowerMock。
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.
推荐答案
Mockito支持更改返回值;这种支持扩展到PowerMockito。只需使用 OngoingStubbing.thenReturn(T值,T ...值)
Mockito supports changing the returned value; this support extends to PowerMockito. Just use 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);
序列中的最后一个返回值(例如:3)决定了进一步连续调用的行为。 / p>
Last return value in the sequence (in example: 3) determines the behavior of further consecutive calls.
所以,在这种情况下,你会这样做:
So, in this case, you would do:
PowerMockito.when(DBUtil.getCurrentCount()).thenReturn(100, 150);
注意:这个答案假设你已经知道如何模拟 static
方法。如果没有,请参阅此问题。
Note: this answer assumes you already know how to mock static
methods. If you do not, see this question.
这篇关于如何在对模拟的不同调用中返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!