How do you assert that a certain exception is thrown in JUnit 4 tests?

前端 未结 30 1960
忘掉有多难
忘掉有多难 2020-11-21 22:23

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFo         


        
30条回答
  •  别那么骄傲
    2020-11-21 23:08

    Additionally to what NamShubWriter has said, make sure that:

    • The ExpectedException instance is public (Related Question)
    • The ExpectedException isn't instantiated in say, the @Before method. This post clearly explains all the intricacies of JUnit's order of execution.

    Do not do this:

    @Rule    
    public ExpectedException expectedException;
    
    @Before
    public void setup()
    {
        expectedException = ExpectedException.none();
    }
    

    Finally, this blog post clearly illustrates how to assert that a certain exception is thrown.

提交回复
热议问题