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())).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return new Foo(args[0])
}
});
Obviously, I can have a field of type Foo and inside answer
set it to the new instance, but is there a nicer way? Something like ArgumentCaptor?
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.
Intended usage:
Looks like you want to observe then
Answer
instances and receive notfications each time theanswer
method is called (which triggers the creation of a newFoo
). So why not invent anObservableAnswer
class:Intended use: