• 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:


    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;
    public class VerifyTest {
        private List<String> mockList;
        public void testMockListAdd() {
            String addString = "some string";
            //verify that the add method was called with argument 'some string'
        public void testMockListAddMultiple() {
            String addString = "some string multiple";
            //verify that the add method was called with argument 'some string'
            verify(mockList, times(3)).add(addString);

    Related Post

    • sushil sinha


    • david lopes

      nice! thx!

    • Bacillus Bulgaricus

      The example is pointless. You explicitly call method A than you verify that the same method A is called. Instead it’s better for the example to call method A and then verify that method B was called.