Bird
Raised Fist0
JUnittesting~15 mins

Argument captors in JUnit - Build an Automation Script

Choose your learning style10 modes available
Verify method argument using ArgumentCaptor in JUnit
Preconditions (2)
Step 1: Mock the repository dependency
Step 2: Call the service method that internally calls the repository method
Step 3: Capture the argument passed to the repository method using ArgumentCaptor
Step 4: Verify that the repository method was called once
Step 5: Assert that the captured argument matches the expected value
✅ Expected Result: The test passes confirming the repository method was called with the correct argument
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Verify repository method call count
Assert captured argument value
Best Practices:
Use @ExtendWith(MockitoExtension.class) for Mockito support
Use ArgumentCaptor to capture method arguments
Use verify() to check method invocation
Keep test methods focused and clear
Automated Solution
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

    @Mock
    UserRepository userRepository;

    @InjectMocks
    UserService userService;

    @Test
    void testCreateUser_callsRepositoryWithCorrectUser() {
        // Arrange
        User expectedUser = new User("Alice", "alice@example.com");

        // Act
        userService.createUser("Alice", "alice@example.com");

        // Assert
        ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
        verify(userRepository, times(1)).save(userCaptor.capture());
        User capturedUser = userCaptor.getValue();

        assertEquals(expectedUser.getName(), capturedUser.getName());
        assertEquals(expectedUser.getEmail(), capturedUser.getEmail());
    }
}

// Supporting classes
class User {
    private String name;
    private String email;

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() { return name; }
    public String getEmail() { return email; }
}

interface UserRepository {
    void save(User user);
}

class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void createUser(String name, String email) {
        User user = new User(name, email);
        userRepository.save(user);
    }
}

This test uses Mockito with JUnit 5 to verify that the UserService calls the save method of UserRepository with the correct User object.

We use @ExtendWith(MockitoExtension.class) to enable Mockito annotations.

The @Mock annotation creates a mock UserRepository. The @InjectMocks annotation creates a UserService instance and injects the mock repository.

In the test method, we call createUser on the service. Then we use ArgumentCaptor to capture the User object passed to save.

We verify that save was called exactly once. Then we assert that the captured User has the expected name and email.

This approach helps us check the exact argument passed to a mocked method, which is useful when the argument is created inside the method under test.

Common Mistakes - 4 Pitfalls
Not using ArgumentCaptor and instead verifying only method call count
Using raw Mockito verify without specifying times(1)
Not initializing mocks with MockitoExtension or MockitoAnnotations
{'mistake': 'Capturing argument but not asserting its values', 'why_bad': 'Capturing alone does not verify correctness; assertions are needed to confirm expected behavior.', 'correct_approach': "After capturing, assert the argument's fields or properties."}
Bonus Challenge

Now add data-driven testing with 3 different user inputs to verify the repository is called correctly each time

Show Hint

Practice

(1/5)
1. What is the main purpose of using an ArgumentCaptor in JUnit tests with Mockito?
easy
A. To capture and inspect the arguments passed to a mocked method
B. To create a mock object for testing
C. To verify the number of times a method was called
D. To stub the return value of a method

Solution

  1. Step 1: Understand ArgumentCaptor role

    An ArgumentCaptor is used to catch the actual arguments passed to a mock's method during test execution.
  2. Step 2: Differentiate from other Mockito features

    Unlike mocks or verify count, ArgumentCaptor focuses on capturing and inspecting method arguments.
  3. Final Answer:

    To capture and inspect the arguments passed to a mocked method -> Option A
  4. Quick Check:

    ArgumentCaptor captures arguments [OK]
Hint: ArgumentCaptor catches method inputs for checking [OK]
Common Mistakes:
  • Confusing ArgumentCaptor with mock creation
  • Thinking it counts method calls
  • Assuming it stubs return values
2. Which of the following is the correct way to declare an ArgumentCaptor for a String argument in JUnit with Mockito?
easy
A. ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
B. ArgumentCaptor captor = new ArgumentCaptor<String>();
C. ArgumentCaptor<String> captor = new ArgumentCaptor<>();
D. ArgumentCaptor<String> captor = ArgumentCaptor.capture(String.class);

Solution

  1. Step 1: Recall ArgumentCaptor creation syntax

    The correct way is to use the static method forClass() with the class type.
  2. Step 2: Check each option for syntax correctness

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); uses ArgumentCaptor.forClass(String.class), which is correct. Options B and C incorrectly use constructors, which are not public. ArgumentCaptor<String> captor = ArgumentCaptor.capture(String.class); uses a non-existent method capture() for creation.
  3. Final Answer:

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); -> Option A
  4. Quick Check:

    Use forClass() to create captor [OK]
Hint: Use ArgumentCaptor.forClass(Type.class) to declare captor [OK]
Common Mistakes:
  • Trying to instantiate ArgumentCaptor with new
  • Using non-existent capture() method
  • Omitting the class type in forClass()
3. Given the following code snippet, what will be the captured argument value?
List<String> list = mock(List.class);
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
list.add("hello");
verify(list).add(captor.capture());
String captured = captor.getValue();
medium
A. null
B. "hello"
C. "captor"
D. Throws an exception

Solution

  1. Step 1: Understand the mock and method call

    The mock list has add("hello") called, so "hello" is passed as argument.
  2. Step 2: Verify and capture argument

    The verify(list).add(captor.capture()) captures the argument passed to add(), which is "hello".
  3. Final Answer:

    "hello" -> Option B
  4. Quick Check:

    Captured argument matches method call input [OK]
Hint: Captured value equals argument passed to mock method [OK]
Common Mistakes:
  • Assuming captor captures method name
  • Expecting null if not stubbed
  • Thinking it throws exception without stubbing
4. Identify the error in the following test code using ArgumentCaptor:
ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
verify(mockedList).add(captor.capture());
mockedList.add(5);
Integer value = captor.getValue();
medium
A. ArgumentCaptor should be declared after method call
B. No error, code is correct
C. Captor must be reset before use
D. The verify call is before the actual method call

Solution

  1. Step 1: Analyze order of method call and verify

    The verify() call must come after the actual method call to check interactions.
  2. Step 2: Identify the mistake

    Here, verify() is called before mockedList.add(5), so no interaction is recorded yet.
  3. Final Answer:

    The verify call is before the actual method call -> Option D
  4. Quick Check:

    Verify after method call [OK]
Hint: Always call verify() after the method under test [OK]
Common Mistakes:
  • Calling verify before method invocation
  • Assuming captor resets automatically
  • Declaring captor after verify
5. You want to verify that a mocked service method was called twice with different String arguments, and capture both arguments for assertions. Which approach correctly uses ArgumentCaptor to achieve this?
hard
A. Use ArgumentCaptor only once; it cannot capture multiple calls
B. Create two separate ArgumentCaptors and verify each call separately
C. Use a single ArgumentCaptor and call getAllValues() after verifying two calls
D. Capture arguments by stubbing the method instead of verify

Solution

  1. Step 1: Understand multiple call verification with ArgumentCaptor

    A single ArgumentCaptor can capture all arguments from multiple calls using getAllValues().
  2. Step 2: Evaluate options for capturing multiple arguments

    Use a single ArgumentCaptor and call getAllValues() after verifying two calls correctly uses one captor and retrieves all captured arguments. Create two separate ArgumentCaptors and verify each call separately is unnecessary and verbose. Use ArgumentCaptor only once; it cannot capture multiple calls is false; captor supports multiple captures. Capture arguments by stubbing the method instead of verify is incorrect because stubbing does not capture arguments.
  3. Final Answer:

    Use a single ArgumentCaptor and call getAllValues() after verifying two calls -> Option C
  4. Quick Check:

    Single captor + getAllValues() captures multiple calls [OK]
Hint: Use getAllValues() on one captor for multiple calls [OK]
Common Mistakes:
  • Creating multiple captors unnecessarily
  • Thinking captor captures only one call
  • Trying to capture arguments via stubbing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard