We use verification times to check how many times a method was called in a test. This helps us make sure our code behaves as expected.
0
0
Verification times (times, never, atLeast) in JUnit
Introduction
When you want to confirm a method was called exactly a certain number of times.
When you want to check that a method was never called during a test.
When you want to verify a method was called at least a minimum number of times.
Syntax
JUnit
verify(mockObject, times(n)).methodCall(); verify(mockObject, never()).methodCall(); verify(mockObject, atLeast(n)).methodCall();
verify checks the method call on the mock object.
times(n) means exactly n times, never() means zero times, and atLeast(n) means n or more times.
Examples
Check that
add("item") was called exactly twice on mockList.JUnit
verify(mockList, times(2)).add("item");
Check that
clear() was never called on mockList.JUnit
verify(mockList, never()).clear();
Check that
add("item") was called at least once on mockList.JUnit
verify(mockList, atLeast(1)).add("item");
Sample Program
This test creates a mock list and calls add("apple") twice. It then verifies the method calls using times(2), never(), and atLeast(1). If all verifications pass, it prints a success message.
JUnit
import static org.mockito.Mockito.*; import java.util.List; public class VerificationTimesTest { public static void main(String[] args) { List<String> mockList = mock(List.class); mockList.add("apple"); mockList.add("apple"); // Verify add("apple") called exactly 2 times verify(mockList, times(2)).add("apple"); // Verify clear() was never called verify(mockList, never()).clear(); // Verify add("apple") called at least once verify(mockList, atLeast(1)).add("apple"); System.out.println("All verifications passed."); } }
OutputSuccess
Important Notes
If a verification fails, Mockito throws an exception and the test fails.
Use never() to ensure no unwanted calls happen.
atLeast(n) is useful when you expect multiple calls but exact count is not fixed.
Summary
Verification times help check how often methods are called in tests.
times(n) means exactly n calls, never() means zero calls, and atLeast(n) means n or more calls.
These checks make tests more precise and reliable.