Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito ArgumentMatcher lambda function with parameter not recognizing method

I'm trying to learn Mockito framework and implementing some mocks. Currently, I want to use ArgumentMatcher to check if the passed object matches. I saw that in the past this was possible by creating a new class that extends ArgumentMatcher. However, now it's possible to use Java 8 lambda functions. This is how I'm trying to implement it:

private ArgumentMatcher<User> matchUser(User user) {
    return u -> u != null && user.getId() == u.getId();
}

IntelliJ is giving me an error, as it's telling that u doesn't have the getId method. Should't u type be inferred to User?

like image 228
Gustavo Amgarten Avatar asked Jul 29 '26 01:07

Gustavo Amgarten


1 Answers

You have Mockito version 1.x, where ArgumentMatcher is an abstract class. As of Mockito 2.x, they changed it to be an interface, allowing to use lambdas.

The source code of ArgumentMatcher shows that:

  • Branch release-2.x on GitHub
  • Branch release-1.x on GitHub

If you fix your dependencies to a more recent version of Mockito, it'll work.

like image 150
MC Emperor Avatar answered Jul 31 '26 14:07

MC Emperor



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!