Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify that specific class method was passed as parameter?

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()))
like image 604
Anton Avatar asked Nov 09 '22 06:11

Anton


1 Answers

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.

like image 93
Kevin Welker Avatar answered Nov 14 '22 21:11

Kevin Welker