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

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

    To solve the same problem I did set up a small project: http://code.google.com/p/catch-exception/

    Using this little helper you would write

    verifyException(foo, IndexOutOfBoundsException.class).doStuff();
    

    This is less verbose than the ExpectedException rule of JUnit 4.7. In comparison to the solution provided by skaffman, you can specify in which line of code you expect the exception. I hope this helps.

提交回复
热议问题