I wanted to do something similar, but with a spy object, not a layout. In particular, given the spy object, I want to commit the return value. Based on Andreas_D answer, here is what I came up with.
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 Use:
// 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 capture the return values from spiedDao.find() final ResultCaptor<QueryResult> resultCaptor = new ResultCaptor<>(); doAnswer(resultCaptor).when(spiedDao).find(any(User.class), any(Query.class)); // execute once service.run(); assertThat(resultCaptor.getResult()).isEqualTo(); /// change conditions /// // execute again service.run(); assertThat(resultCaptor.getResult()).isEqualTo();
Jeff fairley
source share