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

前端 未结 12 2004
广开言路
广开言路 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条回答
  •  -上瘾入骨i
    2020-12-12 09:05

    Actually, the best usage is with try/catch. Why? Because you can control the place where you expect the exception.

    Consider this example:

    @Test (expected = RuntimeException.class)
    public void someTest() {
       // test preparation
       // actual test
    }
    

    What if one day the code is modified and test preparation will throw a RuntimeException? In that case actual test is not even tested and even if it doesn't throw any exception the test will pass.

    That is why it is much better to use try/catch than to rely on the annotation.

提交回复
热议问题