Home > other >  Verify overloaded method execution in Mockito
Verify overloaded method execution in Mockito

Time:11-15

I am trying to make Mockito validate a call to library function which code cannot be changed else would have changed signature of varargs to publish(Record record, Record... records)

publish(Record record)
publish(Record... records)  

To validate execution of second function, using following code

verify(publisher).publish(ArgumentMatchers.<Record>any());

However above call always keep try to check for publish call with NonArgs function and fails. Any suggestions how to make Mockito to check for var args function.

Used mockito Version for this test is 3.11.2

CodePudding user response:

You need to pick a right overload when you call the verify method.

Mockito.verify(publisher).publish(ArgumentMatchers.<MyRecord[]>any());

By specifying ArgumentMatchers.<MyRecord>any() you picked the wrong overload .

Notes:

  • any() implements VarargMatcher - a special marker interface meaning that this matcher can be used mo match varargs
  • each vararg is matched by VarargMatcher separately, in a for loop

Other notes:

  • Record is a keyword in modern Java, you might consider renaming your class to sth different
  • Related