mockito - Java unit test mock a method with predicate as an argument -


i have 2 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 unit test, need mock classa, use mockito's mock method following:

classa mockobjecta = mockito.mock(classa.class); mockito.when(mockobjecta).methoda("some id", predicatesprovider.isuservalid()).thenreturn("something"); 

mockito couldn't find signature match.

the java.lang.assertionerror: expected:<predicatesprovider$$lambda$5/18242360@815b41f> was:<predicatesprovider$$lambda$5/18242360@5542c4ed> 

this kind of simplified version of trying achieve. guess problem equals() function of predicate. idea how mock method has predicate argument?

thanks

i see 4 possible solutions:

  1. always return exact same predicate instance isuservalid() method. since predicate stateless, that's not problem.

  2. implement predicate real class, implementing equals() , hashcode(). that's overkill compared first solution.

  3. use matcher:

     mockito.when(mockobjecta).methoda(mockito.eq("some id"), mockito.<predicate<user>>anyobject()).thenreturn("something"); 
  4. don't use static method create predicate, injectable factory, can mock , verify:

    predicatesprovider mockpredicatesprovider = mock(predicatesprovider.class); predicate<user> expectedpredicate = (u -> true); when(mockpredicatesprovider.isuservalid()).thenreturn(expectedpredicate); when(mockobjecta).methoda("some id", expectedpredicate).thenreturn("something"); 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -