我有以下代码,它从数据库中获取当前计数器值。然后它更新数据库中的计数器,然后再次检索值。
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。
最佳答案
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.
因此,在这种情况下,您可以:
PowerMockito.when(DBUtil.getCurrentCount()).thenReturn(100, 150);
注意:此答案假定您已经知道如何模拟 static
方法。如果您不这样做,请参阅 this question .
关于java - 如何在对模拟的不同调用中返回不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430387/