If I mock a method to return a new instance of some object, how can I capture the returned instance?
E.g.:
when(mock.someMethod(anyString())).thenAnswe
I wanted to do something similar, but with a spied object rather than a mock. Specifically, given a spied object, I want to capture the return value. Based on Andreas_D's answer, here's what I came up with.
public class ResultCaptor 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:
// spy our dao
final Dao spiedDao = spy(dao);
// instantiate a service that does some stuff, including a database find
final Service service = new Service(spiedDao);
// let's capture the return values from spiedDao.find()
final ResultCaptor resultCaptor = new ResultCaptor<>();
doAnswer(resultCaptor).when(spiedDao).find(any(User.class), any(Query.class));
// execute once
service.run();
assertThat(resultCaptor.getResult()).isEqualTo(/* something */);
/// change conditions ///
// execute again
service.run();
assertThat(resultCaptor.getResult()).isEqualTo(/* something different */);