How do I return different values on different calls to a mock?

后端 未结 1 1541
生来不讨喜
生来不讨喜 2021-02-20 17:18

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 curren         


        
相关标签:
1条回答
  • 2021-02-20 18:05

    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);
    

    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);
    

    Note: this answer assumes you already know how to mock static methods. If you do not, see this question.

    0 讨论(0)
提交回复
热议问题