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

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

    It depends on the JUnit version and what assert libraries you use.

    • For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984
    • If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984

    The original answer for JUnit <= 4.12 was:

    @Test(expected = IndexOutOfBoundsException.class)
    public void testIndexOutOfBoundsException() {
    
        ArrayList emptyList = new ArrayList();
        Object o = emptyList.get(0);
    
    }
    

    Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.

    Reference :

    • JUnit Test-FAQ

提交回复
热议问题