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

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

    in junit, there are four ways to test exception.

    junit5.x

    • for junit5.x, you can use assertThrows as following

      @Test
      public void testFooThrowsIndexOutOfBoundsException() {
          Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());
          assertEquals("expected messages", exception.getMessage());
      }
      

    junit4.x

    • for junit4.x, use the optional 'expected' attribute of Test annonation

      @Test(expected = IndexOutOfBoundsException.class)
      public void testFooThrowsIndexOutOfBoundsException() {
          foo.doStuff();
      }
      
    • for junit4.x, use the ExpectedException rule

      public class XxxTest {
          @Rule
          public ExpectedException thrown = ExpectedException.none();
      
          @Test
          public void testFooThrowsIndexOutOfBoundsException() {
              thrown.expect(IndexOutOfBoundsException.class)
              //you can test the exception message like
              thrown.expectMessage("expected messages");
              foo.doStuff();
          }
      }
      
    • you also can use the classic try/catch way widely used under junit 3 framework

      @Test
      public void testFooThrowsIndexOutOfBoundsException() {
          try {
              foo.doStuff();
              fail("expected exception was not occured.");
          } catch(IndexOutOfBoundsException e) {
              //if execution reaches here, 
              //it indicates this exception was occured.
              //so we need not handle it.
          }
      }
      
    • so

      • if you like junit 5, then you should like the 1st one
      • the 2nd way is used when you only want test the type of exception
      • the first and last two are used when you want test exception message further
      • if you use junit 3, then the 4th one is preferred
    • for more info, you can read this document and junit5 user guide for details.

提交回复
热议问题