In Mockito, you can mock void methods by using the "doAnswer()" method from the "org.mockito.stubbing.Answer" class. This method allows you to specify a custom implementation for a void method that will be executed when the method is called on a mock.
Here is an example of how to mock a void method using the "doAnswer()" method in Java:
import static org.mockito.Mockito.*;
import org.mockito.stubbing.Answer;
// Create a mock object
MyClass myClass = mock(MyClass.class);
// Use doAnswer to specify a custom implementation for the void method
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
// Perform custom logic here with the arguments passed to the method
System.out.println("Method called with arguments: " + Arrays.toString(args));
return null;
}
}).when(myClass).myVoidMethod(anyInt(), anyString());
// Call the void method on the mock object
myClass.myVoidMethod(123, "hello");
// Verify that the void method was called on the mock object
verify(myClass).myVoidMethod(123, "hello");
No comments:
Post a Comment