0
0
JUnittesting~10 mins

Verification times (times, never, atLeast) in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies how many times a mock method is called using JUnit with Mockito. It checks that a method is called exactly twice, never called with a certain argument, and called at least once.

Test Code - JUnit with Mockito
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

public class VerificationTimesTest {

    interface Service {
        void performAction(String input);
    }

    @Test
    void testVerificationTimes() {
        Service mockService = mock(Service.class);

        // Call performAction twice with "hello"
        mockService.performAction("hello");
        mockService.performAction("hello");

        // Call performAction once with "world"
        mockService.performAction("world");

        // Verify performAction called exactly twice with "hello"
        verify(mockService, times(2)).performAction("hello");

        // Verify performAction never called with "test"
        verify(mockService, never()).performAction("test");

        // Verify performAction called at least once with "world"
        verify(mockService, atLeast(1)).performAction("world");
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized, Mockito mock created for Service interface-PASS
2Calls mockService.performAction("hello") twiceMock records two calls with argument "hello"-PASS
3Calls mockService.performAction("world") onceMock records one call with argument "world"-PASS
4Verifies performAction called exactly twice with "hello" using verify(mockService, times(2))Mockito checks recorded calls for "hello" argumentExactly 2 calls with "hello" foundPASS
5Verifies performAction never called with "test" using verify(mockService, never())Mockito checks recorded calls for "test" argumentNo calls with "test" foundPASS
6Verifies performAction called at least once with "world" using verify(mockService, atLeast(1))Mockito checks recorded calls for "world" argumentAt least 1 call with "world" foundPASS
7Test ends successfullyAll verifications passed-PASS
Failure Scenario
Failing Condition: If performAction is called fewer or more times than expected for a verification, or called with unexpected arguments
Execution Trace Quiz - 3 Questions
Test your understanding
What does verify(mockService, never()).performAction("test") check?
AThat performAction was called exactly once with argument "test"
BThat performAction was called at least once with argument "test"
CThat performAction was never called with argument "test"
DThat performAction was called twice with argument "test"
Key Result
Use verification times to precisely check how many times a mock method is called, which helps catch unexpected behavior in your code.