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

前端 未结 30 1961
忘掉有多难
忘掉有多难 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:18

    Be careful using expected exception, because it only asserts that the method threw that exception, not a particular line of code in the test.

    I tend to use this for testing parameter validation, because such methods are usually very simple, but more complex tests might better be served with:

    try {
        methodThatShouldThrow();
        fail( "My method didn't throw when I expected it to" );
    } catch (MyException expectedException) {
    }
    

    Apply judgement.

提交回复
热议问题