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
Looks like you want to observe and then Answer
instances, and receive notifications each time the answer
method is called (which triggers the creation of a new Foo
). So why not invent an ObservableAnswer
class:
public abstract class ObservableAnswer implements Answer {
private Listener[] listeners; // to keep it very simple...
public ObservableAnswer(Listener...listeners) {
this.listeners = listeners;
}
@Override
public Object answer(InvocationOnMock invocation) {
Object answer = observedAnswer(invocation);
for (Listener listener:listeners) {
listener.send(answer);
}
return answer;
}
// we'll have to implement this method now
public abstract Object observedAnswer(InvocationOnMock invocation);
}
Intended use:
Listener[] myListeners = getListeners(); // some magic (as usual)
when(mock.someMethod(anyString())).thenAnswer(new ObservableAnswer(myListeners) {
Object observedAnswer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return new Foo(args[0])
}
});