ghostrider
ghostrider

Reputation: 2238

AssertThrows in JUNIT5

I am trying to learn assertThrows in junit5, it takes Executable as 2nd arg which has a void execute() method. But while going through the example on the same in the below example we are passing it a LAMBDA which returns a double with method double divide(int a , int b). Now how is it possible to pass the below lambda if it does not have the same signature as the execute method of the Excecutable. It should give compile error right?

assertThrows(ArithmeticException.class,() -> m.divide(1, 0),"Failed");

Upvotes: 1

Views: 420

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

() -> m.divide(1, 0)

is treated effectively like

new Executable() {
  @Override public void execute() {
    m.divide(1, 0);
  }
}

The lambda can be treated like an instance of any interface/class with a single abstract method.

Lambdas are always polyexpressions, meaning that their exact type is determined by the context in which they are used.

There is no compatibility issue.

Upvotes: 6

Related Questions