Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take the specifical class for lambda expression, e.g. subclass of the type in method parameters

Tags:

lambda

mockito

I'm trying to add a customized ArgumentMatcher(subclass of Matcher) for mockito testing, following is the code:

when(mockedObject.mockedMethod(
   argThat((int id)-> id > 5 || id < 1 ? false : true)));

but I receives the error :

Multiple non-overriding abstract methods found in interface org.hamcrest.Matcher

I know that the argThat is defined as:

public static <T> T argThat(Matcher<T> matcher)

Can I tell the compiler that I want to use ArgumentMatcher, not Matcher in lambda expression?

Thanks!

like image 250
Peter Peng Avatar asked Sep 12 '25 04:09

Peter Peng


1 Answers

No, what you want is not possible. org.hamcrest.Matcher is not a functional interface. It has multiple non-abstract methods. For example any of these:

  • org.hamcrest.SelfDescribing.describeTo(Description)
  • org.hamcrest.Matcher.matches(Object)

The compiler needs to convert a lambda to an implementation of a functional interface. But ArgumentMatcher itself is already a class.

As a workaround you could create your own version of argThat that receives a java.util.function.Predicate and converts that to a Matcher implementation. However you will loose the support of SelfDescribing and have to live with bad failure descriptions.

like image 120
SpaceTrucker Avatar answered Sep 16 '25 02:09

SpaceTrucker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!