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

前端 未结 12 2003
广开言路
广开言路 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:19

    You could use the @Rule annotation with ExpectedException, like this:

    @Rule
    public ExpectedException expectedEx = ExpectedException.none();
    
    @Test
    public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
        expectedEx.expect(RuntimeException.class);
        expectedEx.expectMessage("Employee ID is null");
    
        // do something that should throw the exception...
        System.out.println("=======Starting Exception process=======");
        throw new NullPointerException("Employee ID is null");
    }
    

    Note that the example in the ExpectedException docs is (currently) wrong - there's no public constructor, so you have to use ExpectedException.none().

提交回复
热议问题