Verify service method called with specific and any arguments using argument matchers
Preconditions (2)
✅ Expected Result: The verification passes confirming the method was called with the expected argument matchers
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class ServiceTest { interface Service { void performAction(String text, Integer number); } @Test void testArgumentMatchers() { Service serviceMock = mock(Service.class); // Call the method with specific arguments serviceMock.performAction("testString", 10); // Verify method called with exact String and any Integer verify(serviceMock).performAction(eq("testString"), anyInt()); // Verify method called with any String and exact Integer verify(serviceMock).performAction(anyString(), eq(10)); } }
This test uses Mockito to create a mock of the Service interface.
We call the performAction method with the arguments "testString" and 10.
Then, we verify two things:
"testString" and any integer (using eq and anyInt).10 (using anyString and eq).This shows how to use argument matchers to flexibly check method calls without requiring exact matches on all parameters.
Using @ExtendWith(MockitoExtension.class) ensures Mockito initializes correctly with JUnit 5.
Now add tests verifying the method is called with any String and any Integer using argument matchers
any() argument matcher do in JUnit Mockito tests?any()any() matcher is used to accept any argument of a given type in method verification or stubbing.eq(), which matches exact values, any() is flexible and matches all values of the specified type.any() = matches any value [OK]eq() matcher is used to match an exact argument value in Mockito verification.eq("test") to verify the method was called with the exact string "test".when(service.process(any(String.class))).thenReturn("done");
String result = service.process("input");result after execution?when clause uses any(String.class) to match any string argument and returns "done".any(String.class), so the stub returns "done".verify(mock).update(eq("data"), any());any() matcher requires a type parameter like any(String.class) to specify the argument type.eq("test").any(Integer.class).eq() and any() for the two arguments.Pass the test and this pattern moves unknown