dimanche 21 mars 2021

How can I test method which throws NullPointerException using JUnit 5

How can I test method which throws NullPointerException using JUnit 5. But I catch this exception in the method, so test is ending with error: "Expected java.lang.NullPointerException to be thrown, but nothing was thrown."

MyClass{
   void myMethod() {
        try {
            throw new NullPointerException();
        }catch(NullPointerException e) {
            //do somthing
        }
   }
}

MyClassTest{  
  @Test 
  void shouldThrowNullPointerException() {
       MyClass odj = new MyClass();
       
       Assertions.assertThrows(NullPointerException.class, () -> obj.myMethod());      
   }
}

Thank you

Aucun commentaire:

Enregistrer un commentaire