Di Zou Di Zou - 1 year ago 56
Java Question

How would I mock a method of a real object and access the method arguments?

I'm using

to write some tests in my Java code. In my test, I have a real object, but I want to mock what happens in one of the methods and be able to access the method arguments.

If I do this:

MyObj spyObj = spy(new MyObj());
doReturn(false).when(spyObj).myMethod(anyObject(), anyObject(), anyList(), anyLong());

I can't access the arguments and do any sort of logic with them.

However, if I use
like so:

when(spyObj.myMethod(anyObject(), anyObject(), anyList(), anyLong())).thenAnswer(invocation -> {
if (invocation.getArguments()[0] == 1) {
// do stuff
return true;
return false;

the real method runs instead of the mocked method. How would I be able to have my test run my mocked method and be able to access the arguments inside the mocked method? Thanks!

Answer Source

The syntax you want is

doAnswer(invocation -> { whatever }).when(spyObj).myMethod( whatever );

This lets you stub a method of a spy, without actually invoking it.