Java unit test mock method with predicate as argument
I have two classes:
ClassA {
public String methodA(String accountId, Predicate<User> predicate) {
// more code
};
}
ClassB {
methodB(){
ClassA objectA = new ClassA();
objectA.methodA("some id", PredicatesProvider.isUserValid());
// more code ...
}
}
class PredicatesProvider {
static Predicate<User> isUserValid(){
return (user) -> {
return user.isValid();
}
}
In my unit test, I need to mock ClassA, so I use the mockito mock method like this:
ClassA mockObjectA = Mockito.mock(ClassA.class);
Mockito.when(mockObjectA).methodA("some id", PredicatesProvider.isUserValid()).thenReturn("something");
Mockito could not find a signature match.
The java.lang.AssertionError: expected:<PredicatesProvider$$Lambda$5/18242360@815b41f> but was:<PredicatesProvider$$Lambda$5/18242360@5542c4ed>
This is sort of a simplified version of what I am trying to achieve. I think this is a problem with the equals () function of the predicate. Any idea how to mock a method that has a predicate argument?
thank
source to share
I see 4 possible solutions:
-
Always return an exact Predicate instance from your method
isUserValid()
. Since the predicate is stateless, this is not a problem. -
Implement Predicate as a real class by implementing equals () and hashCode (). But this is an excess compared to the first solution.
-
Use a connector:
Mockito.when(mockObjectA).methodA(Mockito.eq("some id"), Mockito.<Predicate<User>>anyObject()).thenReturn("something");
-
Don't use a static method to create a predicate, but an injection Factory that you can mock and test:
PredicatesProvider mockPredicatesProvider = mock(PredicatesProvider.class); Predicate<User> expectedPredicate = (u -> true); when(mockPredicatesProvider.isUserValid()).thenReturn(expectedPredicate); when(mockObjectA).methodA("some id", expectedPredicate).thenReturn("something");
source to share