Mockito is a well-known Java-based framework for mocking objects in unit tests. This article will cover a specific use-case about checking if the method has not been called even once.
2. Mockito verify method
Mockito provides a
verify() method that we can call on a mock object to check if specific conditions are met.
Let's have a look at what verifications are available in Mockito.
2.1 Verifying exact number of invocations
To check exact number of method invocation we could
verify(...) method with seconds parameter that could be:
times(x)to verify if method was called x times,
never()to verify if method was never called,
atLeastOnce()to check if method was called at least once,
atLeast(x)to verify if method was called at least x times,
atMost(x)to verify if method was called at most x times.
To verify if the method was called once with a specific argument we could use
Let's check the following example:
In this test we use
List<String> mock to check Mockito's verify method. We created mock object and add two Strings. Test passes because:
verify(list, times(2)).add(anyString());- method
addwas called two times,
verify(list, never()).add("three");- method
threewas never called,
verify(list, never()).remove(anyInt());- method
removewas never called,
verify(list, atLeastOnce()).add(anyString());- method
addwas caled at least two times,
verify(list, atMost(2)).add(anyString());- method
addwas called at most two times,
verify(list, atLeast(2)).add(anyString());- method
addwas called at least two times.
Answering the question given in the title: to verify if the method was never called using Mockito framework we need to use
In this short article, we presented how to use the
verify(...) method with various parameters. The
verify(...) is useful in unit tests where we need to specifically define the number of method invocations.
Test used in this article is available on out GitHub repository.