Java Junit Mockito thenCallRealMethod(), call method with input parameters
In java junit mockito even we mock a class we can use thenCallRealMethod() to execute that method, but when that method has input parameters , parameters are not going in. How we solve this issue
So you method will be like
class YourClass {
public String yourMethod(String s1, int i1) {
....
}
}
If you write like below it will not pass the values inside, even it will go inside and execute the method
Mockito.when(yourMock.yourMethod(Mockito.anyString(), Mockito.anyInt())).thenCallRealMethod()
In Mockito, when mocking a class and using thenCallRealMethod()
to execute a method, the actual method implementation is invoked. However, if the method has input parameters, Mockito does not automatically pass the arguments to the real method. Instead, it uses the default values or null for the parameter types.
If you want to pass specific arguments to the real method when using thenCallRealMethod()
, you can use the Answer
interface along with thenAnswer()
method to customize the behavior. Here's an example:
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
// ...
YourClass yourMock = Mockito.mock(YourClass.class);
Mockito.when(yourMock.yourMethod(Mockito.anyString(), Mockito.anyInt()))
.thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
// Process or modify the arguments as needed
String arg1 = (String) args[0];
int arg2 = (int) args[1];
// Call the real method with the modified arguments
Object result = invocation.callRealMethod();
// Perform any additional processing if necessary
return result;
}
});
In this example, the thenAnswer()
method is used to specify an implementation of the Answer
interface. Inside the answer()
method, you can access the method arguments using invocation.getArguments()
and modify them as needed. Then, you can call the real method using invocation.callRealMethod()
, passing the modified arguments. Finally, you can perform any additional processing and return the result if necessary.
By using thenAnswer()
along with InvocationOnMock
and callRealMethod()
, you can have more control over the behavior of the mocked method, including passing specific arguments to the real method when using thenCallRealMethod()