11

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

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.

1
  • Why is DBUtil static? Inject an instance, then you don't need PowerMock. Commented Sep 7, 2015 at 3:33

1 Answer 1

19

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.