Junit using eq() argument matcher vs passing string directly

Viewed 2216

What is the use of eq() argument matcher if passing the string directly will do the same thing.

e.g. the behaviour of

when(method.foo("test")).thenReturn("bar");

is similar to

when(method.foo(ArgumentMatcher.eq("test"))).thenReturn("bar");

1 Answers

There are more ArgumentMatchers than eq(). Another popular one is any(), but there are many more ArgumentMatchers. They are generally used together to help identify the correct value for the test case. You may not want to check all args in all tests. For example, if there were more params in your code.

when(method.foo(eq("test"), any(Test.class), isNull()).thenReturn("bar");

I agree that eq() seems redundant, but the trick is if one argument uses a matcher all must, so if you want to use one any() you can no longer just put an unwrapped String argument.

Related