0
0
JUnittesting~5 mins

Argument matchers (any, eq) in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of argument matchers like any() and eq() in JUnit testing?
Argument matchers help specify flexible or exact values when verifying or stubbing method calls in tests. any() matches any value of the given type, while eq() matches an exact value.
Click to reveal answer
beginner
How does any() differ from eq() in argument matching?
any() accepts any argument of the specified type without checking its value. eq() requires the argument to exactly match the given value.
Click to reveal answer
beginner
Show a simple example of using eq() in a JUnit test to verify a method call.
Example: <br>
verify(mockObject).someMethod(eq("hello"));
<br>This checks that someMethod was called with the exact string "hello".
Click to reveal answer
intermediate
Why should you avoid mixing raw values and argument matchers in the same method call verification?
Mixing raw values and argument matchers causes errors because the mocking framework expects either all arguments to be matchers or none. Use eq() for exact values to avoid this.
Click to reveal answer
intermediate
What happens if you use any() without specifying the type in JUnit argument matching?
You must specify the type with any(), like any(String.class). Omitting the type causes compilation errors because the matcher needs to know the argument type.
Click to reveal answer
What does eq(5) do in a JUnit mock verification?
AMatches exactly the integer 5
BMatches any argument except 5
CMatches any integer argument
DThrows an error
Which argument matcher would you use to accept any String argument in a method call?
Aeq(String.class)
Bany()
Cany(String.class)
Deq(any())
Why is mixing raw values and argument matchers in the same method call verification problematic?
AIt causes compilation or runtime errors
BIt causes the test to pass always
CIt improves test readability
DIt is recommended for flexibility
What will happen if you write any() without a type in JUnit 5?
AIt matches only primitive types
BIt matches any argument of any type
CIt matches only null values
DIt causes a compilation error
Which of the following is a correct way to verify a method call with any integer argument?
Averify(mock).method(eq(5));
Bverify(mock).method(any(Integer.class));
Cverify(mock).method(eq(any()));
Dverify(mock).method(any());
Explain the difference between any() and eq() argument matchers in JUnit.
Think about flexible vs exact matching.
You got /4 concepts.
    Describe best practices when using argument matchers in JUnit tests.
    Consider consistency and type safety.
    You got /4 concepts.