How to mock void methods with Mockito

/
0 Comments

 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");


In this example, we use the "doAnswer()" method to specify a custom implementation for the myVoidMethod() method of the MyClass mock object. The custom implementation simply prints the arguments passed to the method. Then, we call the myVoidMethod() method on the mock object and verify that it was called using the verify() method.


You may also like

No comments: