0
0
JUnittesting~10 mins

Argument matchers (any, eq) in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies that a method is called with specific argument values using eq() and any argument using any() matchers in JUnit with Mockito. It checks that the service method behaves correctly when called with expected parameters.

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

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

interface UserRepository {
    String findRole(String userId, Boolean active);
}

class UserService {
    UserRepository repo;
    UserService(UserRepository repo) {
        this.repo = repo;
    }
    String getUserRole(String userId, boolean active) {
        return repo.findRole(userId, active);
    }
}

public class UserServiceTest {
    @Test
    void testGetUserRoleWithArgumentMatchers() {
        UserRepository mockRepo = Mockito.mock(UserRepository.class);
        when(mockRepo.findRole(eq("user123"), any(Boolean.class))).thenReturn("admin");

        UserService service = new UserService(mockRepo);
        String role = service.getUserRole("user123", true);

        assertEquals("admin", role);
        verify(mockRepo).findRole(eq("user123"), any(Boolean.class));
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Mockito mock UserRepository createdMock object ready to intercept calls-PASS
3Stub findRole method with eq("user123") and any(Boolean.class) to return "admin"Mock configured to return 'admin' for matching arguments-PASS
4UserService instance created with mock repositoryService ready to call mocked method-PASS
5Call getUserRole("user123", true)Method calls mockRepo.findRole("user123", true)Check that findRole is called with eq("user123") and any(Boolean.class)PASS
6Assert returned role equals "admin"Role variable holds method return valueassertEquals("admin", role)PASS
7Verify mockRepo.findRole called with eq("user123") and any(Boolean.class)Mockito verifies method call argumentsverify(mockRepo).findRole(eq("user123"), any(Boolean.class))PASS
8Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The findRole method is called with arguments that do not match eq("user123") or any(Boolean.class), or the stub is not set correctly.
Execution Trace Quiz - 3 Questions
Test your understanding
What does the matcher eq("user123") do in this test?
AAllows any string argument
BChecks that the argument is not null
CChecks that the argument exactly equals "user123"
DMatches any Boolean argument
Key Result
When using Mockito argument matchers like eq() and any(), always use matchers for all arguments in a method call to avoid errors and ensure precise verification.