How can we replace the method body of a void method of a stub?
Something like this:
interface Foo {
void foo(Integer j);
}
(...)
Foo mockFoo = mock(Foo.class);
Answer<Void> ans = invocation -> {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
};
when(mockFoo.foo(any())).thenAnswer(ans);
(...)
mockFoo.foo(5) // Should print out "called with arguments: [5]"
It is important to be able to access the parameters, and to be able to execute some code that uses those parameters.
We tried doAnswer(ans).when(mockFoo).foo(any());
, but it seems to execute the body of the ans lambda a few times when setting up the mock, and it resets our mockFoo variable to "null" for some weird reason between the .when(mockFoo)
and the .foo(any())
calls.
So effectively:
Foo mockFoo = mock(Foo.class)
// mockFoo is an instance of a Foo$MockitoMock
Foo o = doAnswer(ans).when(mockFoo);
// mockFoo just became null at this point..?!
o.foo(any());
P.S. We are using the VertxUnitRunner
for running the test, but the problem persists with the MockitoJUnitRunner
as well.