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
As an alternative to @JeffFairley's answer, you can leverage AtomicReference
. It will act as a Holder
, but I prefer this over real holders because it's defined in Java's base framework.
// 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()
AtomicReference reference = new AtomicReference<>();
doAnswer(invocation -> {
QueryResult result = (QueryResult)invocation.callRealMethod();
reference.set(result);
return result;
}).when(spiedDao).find(any(User.class), any(Query.class));
// execute once
service.run();
assertThat(reference.get()).isEqualTo(/* something */);
/// change conditions ///
// execute again
service.run();
assertThat(result.get()).isEqualTo(/* something different */);
In my opinion: ResultCaptor is cool stuff that may be integrated in Mockito in the future, is widely reusable and short in syntax. But if you need that sporadically, then few lines of a lambda can be more concise