Mockito is used to test the execution of overloaded methods. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Mockito is used to test the execution of overloaded methods.

I'm attempting to have Mockito validate a call to a library function whose code cannot be altered; otherwise, the signature of varargs would have changed to publish(Record record, Record... records). publish(Record record) publish(Record... records) To test the execution of the second function, use the code below. verify(publisher).publish(ArgumentMatchers.<Record>any()); However, the preceding call always tries to check for a publish call with the NonArgs function and fails. Any ideas on how to make Mockito check for the var args function? For this test, I used mockito 3.11.2. As I looked around, I came across this lesson from here (https://www.scaler.com/topics/marker-interface-in-java/) that featured a similar example that advised selecting the correct overload when using the check function. Furthermore, it states that any() implements VarargMatcher - a specific marker interface, implying that this matcher can be used repeatedly.

13th Apr 2023, 7:46 AM
sarthak jain
sarthak jain - avatar
1 Answer
+ 5
To verify the execution of the publish(Record... records) method using Mockito, you can use the ArgumentMatchers.anyVararg() method instead of ArgumentMatchers.any(). Here's an example: verify(publisher).publish(ArgumentMatchers.anyVararg()); This will match any invocation of the publish method with any number of Record arguments. Note that anyVararg() is a shorthand for argThat(new ArrayContainingMatcher<>(Matchers.any())). If you need to perform more complex matching on the varargs argument, you can use the argThat method with a custom matcher. Also, make sure that you are mocking the correct instance of the publisher object and that the publish method is actually being called in your test code.
13th Apr 2023, 8:01 AM
Sadaam Linux
Sadaam Linux - avatar