Search code examples
javajunitmockito

How can I change the arguments to a method call using Mockito doAnswer?


I have the following method call

public Report retrieveReport(int rowSize){
...
}

and this method call is being done in another class as so

Report report = reportBuilder.retrieveReport(Report.DEFAULT_ROW_SIZE);

As a part of integration testing, I would like to substitute the Report.DEFAULT_ROW_SIZE with my own variety of sizes.

I've tried creating a spy on the ReportBuilder, and then doing the following

int testSize = 5;
doAnswer(invocation -> {
    Object[] args = invocation.getArguments();
    args[0] = testSize;
    return invocation.callRealMethod();
}).when(reportBuilder).retrieveReport(anyInt());

The issue is that when mockito calls the real method, it passes the original argument value, Report.DEFAULT_ROW_SIZE, and doesn't pass in the modified argument testSize. Any idea of what the issue is?


Solution

  • It's not documented whether or not altering the return value of getArguments() will alter the arguments used when callRealMethod() is called.

    What you can try instead is to mock only the call for this specific value to call the method with a different value:

    int testSize = 5;
    doAnswer(invocation -> reportBuilder.retrieveReport(testSize))
            .when(reportBuilder).retrieveReport(Report.DEFAULT_ROW_SIZE);