In class MyClass that I test I have:
public void execute(){
service.call(ThisClass::method1);
}
And following:
void method1(){do 1;}
void method2(){do 2;}
And in test:
@Mock
Service service;
@Test
public void testCallMethod1()
{
MyClass myClass = new MyClass();
myClass.execute();
service.verify(any(Runnable.class));
}
And it works, but, how do I verify that parameter instead of any Runnable was method1 and not method2?
I'm looking for solution that will look like (For example, not really works):
service.verify(eq(MyClass::method1.getRunnable()))
The following works for me:
public class MyTest {
public static class X{
static void method1() {};
static void method2() {};
}
@Test
public void throwAway() {
ExecutorService service = mock(ExecutorService.class);
Runnable command1 = X::method1;
Runnable command2 = X::method2;
service.execute(command1);
verify(service).execute(command1);
verify(service, never()).execute(command2);
}
}
The key was extracting the method reference lambda and using it in both the execution and the verify. Otherwise, each "::" operator produces a distinct lambda instance which doesn't work with equality testing, as some of the comments above discussed the semantics of lambda equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With