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

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

    With Java 8 you can create a method taking a code to check and expected exception as parameters:

    private void expectException(Runnable r, Class clazz) { 
        try {
          r.run();
          fail("Expected: " + clazz.getSimpleName() + " but not thrown");
        } catch (Exception e) {
          if (!clazz.isInstance(e)) fail("Expected: " + clazz.getSimpleName() + " but " + e.getClass().getSimpleName() + " found", e);
        }
      }
    

    and then inside your test:

    expectException(() -> list.sublist(0, 2).get(2), IndexOutOfBoundsException.class);
    

    Benefits:

    • not relying on any library
    • localised check - more precise and allows to have multiple assertions like this within one test if needed
    • easy to use

提交回复
热议问题