Mirai Mann Mirai Mann - 20 days ago 4x
Java Question

How to setup callback for mocked object method call by mockito?

I have method and need to test it:

void update() {

The ordering of calls is important for this scenario. I want to write test like this:

void updateTest(){

Integer CLEAR = 0, UPDATE = 1;
Stack<Integer> callStack = new Stack<>();

Cleaner cleaner = mock(Cleaner.class);
Updator updator = mock(Updator.class);

when(cleaner.clear()).callback(() -> callStack.add(CLEAR));
when(updator.update()).callback(() -> callStack.add(UPDATE));

Some testingObj = new Some(cleaner, updator);

assertEquels(CLEAR, callStack.pop());
assertEquels(UPDATE, callStack.pop());

_cleaner.clear() and _updator.upadate() returns void. It is clear that

when(cleaner.clear()).callback(() -> callStack.add(ClearCall));
when(updator.update()).callback(() -> callStack.add(UpdateCall));

is invalid code. What can I write except those lines for success? How to setup callback for method (with void as type of result) call by mockito?


I recommend you use the InOrder verifier to confirm that the methods are called in the order you want. See here for some of the documentation: http://site.mockito.org/mockito/docs/current/org/mockito/InOrder.html

This example is based on code straight from that documentation:

InOrder inOrder = inOrder(cleaner, updator);