Show List

Verifying method calls with Mockito

Mockito is a popular Java library used for mocking objects during unit testing. One of its key features is the ability to verify method calls on mock objects. Here is an explanation of how to verify method calls with Mockito, along with some examples.

Suppose we have a simple interface called Calculator with two methods: add and subtract. We want to create a mock object of this interface and verify that certain methods are called on it during testing.

To create a mock object, we use the mock method from the Mockito class, like so:

python
Copy code
Calculator calculatorMock = Mockito.mock(Calculator.class);

Now that we have a mock object, we can use it in our test and then verify that certain methods were called on it. There are two ways to verify method calls with Mockito: using verify and using ArgumentCaptor.

Using Verify

The verify method is used to check if a method was called on a mock object. Here is an example of how to use it:

scss
Copy code
Calculator calculatorMock = Mockito.mock(Calculator.class); calculatorMock.add(1, 2); calculatorMock.subtract(5, 3); // Verify that the add method was called with arguments 1 and 2 Mockito.verify(calculatorMock).add(1, 2); // Verify that the subtract method was called with arguments 5 and 3 Mockito.verify(calculatorMock).subtract(5, 3);

In this example, we create a mock object of the Calculator interface, call the add and subtract methods with certain arguments, and then use the verify method to check that the methods were called with those same arguments.

Using ArgumentCaptor

The ArgumentCaptor is used to capture the arguments passed to a method on a mock object. Here is an example of how to use it:

scss
Copy code
Calculator calculatorMock = Mockito.mock(Calculator.class); calculatorMock.add(1, 2); calculatorMock.subtract(5, 3); // Create an ArgumentCaptor for the add method ArgumentCaptor<Integer> addArg1 = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> addArg2 = ArgumentCaptor.forClass(Integer.class); // Verify that the add method was called with arguments that add up to 3 Mockito.verify(calculatorMock).add(addArg1.capture(), addArg2.capture()); int sum = addArg1.getValue() + addArg2.getValue(); assertEquals(3, sum);

In this example, we create a mock object of the Calculator interface, call the add and subtract methods with certain arguments, and then use an ArgumentCaptor to capture the arguments passed to the add method. We then use those captured arguments to verify that they add up to 3.

By using verify and ArgumentCaptor, we can easily test that certain methods were called with certain arguments on mock objects during testing. This is a useful feature for ensuring that our code is behaving correctly and handling expected inputs.


    Leave a Comment


  • captcha text