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

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

    Edit: 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 my other answer for details.

    If you haven't migrated to JUnit 5, but can use JUnit 4.7, you can use the ExpectedException Rule:

    public class FooTest {
      @Rule
      public final ExpectedException exception = ExpectedException.none();
    
      @Test
      public void doStuffThrowsIndexOutOfBoundsException() {
        Foo foo = new Foo();
    
        exception.expect(IndexOutOfBoundsException.class);
        foo.doStuff();
      }
    }
    

    This is much better than @Test(expected=IndexOutOfBoundsException.class) because the test will fail if IndexOutOfBoundsException is thrown before foo.doStuff()

    See this article for details.

提交回复
热议问题