1

When I trying to run this one - all works as expected and test successfully passes:

@Test
public void shouldThrowNPE() {
    @SuppressWarnings("OptionalAssignedToNull") Optional<String> nullOptional = null;
    Assertions.assertThrows(NullPointerException.class, () -> nullOptional.isEmpty());
}

But for this one when I change lambda to method reference I receive NPE and test fails:

@Test
public void shouldThrowNPE() {
    @SuppressWarnings("OptionalAssignedToNull") Optional<String> nullOptional = null;
    Assertions.assertThrows(NullPointerException.class, nullOptional::isEmpty);
}

Could someone give a hint what's wrong here.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183

1 Answers1

0

I am not really expert on interpretation of Java's method reference expressions, but my theory is that a reference to an instance method requires an access to the instance itself BEFORE the method handle, which represents the code to execute, can be created. That's why the NPE occurs before assertThrows(..) will be executed and thus the NPE cannot be caught by it.

johanneslink
  • 4,877
  • 1
  • 20
  • 37