Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic return values with Mockito

Tags:

java

mockito

One typically defines return values for a Mockito mock during compile time, i.e. statically:

MyClass myClass = Mockito.mock(MyClass.class);
when(myClass.myMethod()).thenReturn(0, 100, 200, ...);

Is there a way to do this dynamically by supplying a seed and a function, e.g.:

when(mock.myMethod()).thenReturn(seed, previousVal -> previousVal + 100);
like image 721
beatngu13 Avatar asked Sep 03 '25 09:09

beatngu13


2 Answers

The easiest way may be to combine Mockitos Answer with lambdas, streams and iterators. The resulting code is

Iterator<Integer> values = Stream.iterate(0, n -> n + 100).iterator();
when(myClass.myMethod()).thenAnswer(i -> values.next());

The code can be made a little more efficient if you use an IntStream and a PrimitiveIterator.OfInt as the iterator type, but that is probably overkill for a unit test...

like image 64
Per Huss Avatar answered Sep 04 '25 21:09

Per Huss


Yes, you can return an org.mockito.stubbing.Answer.

class AddingAnswer implements Answer {
    int current = 0;
    public Object answer(InvocationOnMock invocation) {
        int result = current;
        current += 100;
        return result;
    }
}

which you can then wire to your mock like this

Answer answer = new AddingAnswer();
when(myClass.myMethod()).then(answer);

Or in the generic version you want

class DynamicAnswer<T> implements Answer {
    T currentValue;
    UnaryOperator<T> adjustment;
    public DynamicAnswer(T seed, UnaryOperator<T> ad) {
        currentValue = seed;
        adjustment = ad;
    }
    public Object answer(InvocationOnMock invocation) {
        T result = currentValue;
        currentValue = adjustment.apply(currentValue);
        return result;
    }
}
like image 31
daniu Avatar answered Sep 04 '25 21:09

daniu