Verify a method is called two times with Mockito

December 22, 2020 No comments Mockito Library Verify Times

1. Introduction

In this short article, we are going to present a way to verify a method is called two times using the Mockito testing framework. Verifying several method calls are common assertions used in unit tests.

2. Using Mockito verify(...) and times() methods

Luckily, the Mockito framework is fully prepared for such verifications. It comes with dedicated methods that allow us to check the number of method calls:

  • times(x) - methods was called many times,
  • never() - method was never called,
  • atLeastOnce() - method was called at least once,
  • atLeast(x) - method was called at least x times,
  • atMost(x) - method was called at most x times.

These methods are used in verify(...) as a second parameter for example:

verify(mock, times(2)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(4)).someMethod("was called at least twice");
verify(mock, atMost(2)).someMethod("was called at most 3 times");

To check if method was called exactly two times you need to use the Mockito.verify(..., times(2)) method like in the following example:

package com.frontbackend.libraries.mockito;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;

import java.util.List;

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

@RunWith(MockitoJUnitRunner.class)
public class MockitoMockTest {

    @Mock
    private List<String> mock;

    @Test
    public void shouldAddItemsToList() {
        mock.add("one");
        mock.add("two");

        Mockito.verify(mock, times(2))
               .add(anyString()); // method was called exactly 2 times

        Mockito.verify(mock, atLeast(2))
               .add(anyString()); // method was called at least 2 times
    }
}

3. Conclusion

In this article, we presented how to check if a method was called two times with Mockito library. We showed that Mockito allows multiple verifications of a certain behavior if it happened at least once, an exact number of times, or never.

{{ message }}

{{ 'Comments are closed.' | trans }}