Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate the return value when calling a mocked object's method

Using Mockito, is there a way to spy() on an object and verify that an object is called a given # of times with the specified arugments AND that it returns an expected value for these calls?

I'd like to do something like the following:

class HatesTwos {
  boolean hates(int val) {
    return val == 2;
  }
}

HatesTwos hater = spy(new HatesTwos());
hater.hates(1);
assertFalse(verify(hater, times(1)).hates(1));

reset(hater);
hater.hates(2);
assertTrue(verify(hater, times(1)).hates(2));
like image 462
Chris Morris Avatar asked Sep 20 '13 00:09

Chris Morris


1 Answers

You could use the Answer interface to capture a real response.

public class ResultCaptor<T> implements Answer {
    private T result = null;
    public T getResult() {
        return result;
    }

    @Override
    public T answer(InvocationOnMock invocationOnMock) throws Throwable {
        result = (T) invocationOnMock.callRealMethod();
        return result;
    }
}

Intended usage:

class HatesTwos {
    boolean hates(int val) {
        return val == 2;
    }
}

HatesTwos hater = spy(new HatesTwos());

// let's capture the return values from hater.hates(int)
ResultCaptor<Boolean> hateResultCaptor = new ResultCaptor<>();
doAnswer(hateResultCaptor).when(hater).hates(anyInt());

hater.hates(1);
verify(hater, times(1)).hates(1);
assertFalse(hateResultCaptor.getResult());

reset(hater);

hater.hates(2);
verify(hater, times(1)).hates(2);
assertTrue(hateResultCaptor.getResult());
like image 125
Jeff Fairley Avatar answered Nov 14 '22 21:11

Jeff Fairley