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

前端 未结 30 1997
忘掉有多难
忘掉有多难 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 22:52

    JUnit framework has assertThrows() method:

    ArithmeticException exception = assertThrows(ArithmeticException.class, () ->
        calculator.divide(1, 0));
    assertEquals("/ by zero", exception.getMessage());
    
    • for JUnit 5 it's in org.junit.jupiter.api.Assertions class;
    • for JUnit 4.13 it's in org.junit.Assert class;
    • for earlier versions of JUnit 4: just add reference on org.junit.jupiter:junit-jupiter-api to your project and you'll get perfectly well working version from JUnit 5.

提交回复
热议问题