How do I assert my exception message with JUnit Test annotation?

前端 未结 12 2032
广开言路
广开言路 2020-12-12 08:53

I have written a few JUnit tests with @Test annotation. If my test method throws a checked exception and if I want to assert the message along with the exceptio

12条回答
  •  误落风尘
    2020-12-12 09:28

    In JUnit 4.13 you can do:

    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertThrows;
    
    ...
    
    @Test
    void exceptionTesting() {
      IllegalArgumentException exception = assertThrows(
        IllegalArgumentException.class, 
        () -> { throw new IllegalArgumentException("a message"); }
      );
    
      assertEquals("a message", exception.getMessage());
    }
    

    This also works in JUnit 5 but with different imports:

    import static org.junit.jupiter.api.Assertions.assertEquals;
    import static org.junit.jupiter.api.Assertions.assertThrows;
    
    ...
    

提交回复
热议问题