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

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

    Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows() (for JUnit 5) and Assert.assertThrows() (for JUnit 4.13). See the Junit 5 User Guide.

    Here is an example that verifies an exception is thrown, and uses Truth to make assertions on the exception message:

    public class FooTest {
      @Test
      public void doStuffThrowsIndexOutOfBoundsException() {
        Foo foo = new Foo();
    
        IndexOutOfBoundsException e = assertThrows(
            IndexOutOfBoundsException.class, foo::doStuff);
    
        assertThat(e).hasMessageThat().contains("woops!");
      }
    }
    

    The advantages over the approaches in the other answers are:

    1. Built into JUnit
    2. You get a useful exception message if the code in the lambda doesn't throw an exception, and a stacktrace if it throws a different exception
    3. Concise
    4. Allows your tests to follow Arrange-Act-Assert
    5. You can precisely indicate what code you are expecting to throw the exception
    6. You don't need to list the expected exception in the throws clause
    7. You can use the assertion framework of your choice to make assertions about the caught exception

    A similar method will be added to org.junit Assert in JUnit 4.13.

提交回复
热议问题