How to use Verify in Mockito

When doing unit test, you do some assertions to check the equality between your expected result and the actual result. When you use mock objects in unit test, you may also need no to verify in Mockito that the mock object had done specific methods.

Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use:

verify(mockObject).someMethodOfMockObject(someArgument);

If the method was called multiple times, and you want to verify that it was called for specific times, lets say 3 times, then we use:

verify(mockObject, times(3)).someMethodOfMockObject(someArgument);

times() means the number of invocations you expect.

To better understand how verify in mockito works, check the example below.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VerifyTest {

    @Mock
    private List<String> mockList;

    @Test
    public void testMockListAdd() {
        String addString = "some string";
        mockList.add(addString);

        //verify that the add method was called with argument 'some string'
        verify(mockList).add(addString);
    }

    @Test
    public void testMockListAddMultiple() {
        String addString = "some string multiple";
        mockList.add(addString);
        mockList.add(addString);
        mockList.add(addString);

        //verify that the add method was called with argument 'some string'
        verify(mockList, times(3)).add(addString);
    }
}

Share this tutorial!