0
0
JUnittesting~10 mins

Argument captors in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies that a method correctly calls a dependency with the expected argument by capturing the argument passed to a mocked method using an argument captor.

Test Code - JUnit + Mockito
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

class UserServiceTest {

    interface UserRepository {
        void saveUser(String username);
    }

    static class UserService {
        private final UserRepository repo;

        UserService(UserRepository repo) {
            this.repo = repo;
        }

        void registerUser(String username) {
            // Some logic before saving
            repo.saveUser(username);
        }
    }

    @Test
    void testRegisterUserCapturesArgument() {
        UserRepository mockRepo = mock(UserRepository.class);
        UserService service = new UserService(mockRepo);

        service.registerUser("alice");

        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
        verify(mockRepo).saveUser(captor.capture());

        String capturedArg = captor.getValue();
        assertEquals("alice", capturedArg);
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes the test class UserServiceTest-PASS
2Creates a mock UserRepository using MockitomockRepo is a mock object that records interactions-PASS
3Creates UserService instance with mockRepo injectedUserService instance ready to use mockRepo-PASS
4Calls registerUser("alice") on UserServiceInside registerUser, calls mockRepo.saveUser("alice")-PASS
5Creates ArgumentCaptor for String classArgumentCaptor ready to capture String arguments-PASS
6Verifies mockRepo.saveUser was called and captures the argumentCaptured argument is stored inside captorVerify that saveUser was called once with any String argumentPASS
7Retrieves captured argument and asserts it equals "alice"Captured argument is "alice"assertEquals("alice", capturedArg)PASS
8Test ends successfullyTest passed with all assertions met-PASS
Failure Scenario
Failing Condition: The method saveUser was not called or called with a different argument than expected
Execution Trace Quiz - 3 Questions
Test your understanding
What does the ArgumentCaptor capture in this test?
AThe number of times saveUser was called
BThe return value of saveUser method
CThe argument passed to the mockRepo.saveUser method
DThe exception thrown by saveUser
Key Result
Using argument captors helps verify that methods are called with the correct data, improving test accuracy beyond just checking if a method was called.