2015-09-07 46 views
5

我有以下代码从DB获取当前计数器值。然后它更新数据库中的计数器,然后再次检索该值。如何在模拟的不同调用中返回不同的值?

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。

+0

为什么'DBUtil'是静态的?注入一个实例,那么你不需要PowerMock。 – durron597

回答

10

Mockito支持更改返回值;此支持扩展到PowerMockito。只需使用OngoingStubbing.thenReturn(T value, T... values)

OngoingStubbing<T> thenReturn(T value, T... values) 

设置连续的返回值时,该方法被调用来返回。
E.g:在序列中

when(mock.someMethod()).thenReturn(1, 2, 3); 

最后返回值(例如在:3)确定的进一步连续调用的行为。

所以,在这种情况下,你会怎么做:

PowerMockito.when(DBUtil.getCurrentCount()).thenReturn(100, 150); 

注:这个答案假定您已经知道如何嘲笑static方法。如果您没有,请参阅this question