How to verify that a specific class method has been passed as a parameter?

In the MyClass class that I'm testing, I have:

public void execute(){ service.call(ThisClass::method1); } 

And further:

 void method1(){do 1;} void method2(){do 2;} 

And in the test:

 @Mock Service service; @Test public void testCallMethod1() { MyClass myClass = new MyClass(); myClass.execute(); service.verify(any(Runnable.class)); } 

And it works, but how can I verify that this parameter instead of any Runnable was method1, not method2?

I am looking for a solution that will look (for example, not working):

 service.verify(eq(MyClass::method1.getRunnable())) 
+5
source share
1 answer

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 to extract a reference to the lambda method and use it both in execution and in validation. Otherwise, each "::" operator creates a separate lambda instance that does not work with equality checking, as some of the comments above discussed the semantics of lambda equality.

+1
source

Source: https://habr.com/ru/post/1259504/


All Articles