JUnit Exception Testing

前端 未结 5 536
广开言路
广开言路 2020-12-14 19:54

Edit: Not JUnit 4 available at this time.

Hi there,

I have a question about \"smart\" exception testing with JUnit. At this time, I do it like this:

5条回答
  •  醉话见心
    2020-12-14 20:22

    If you have an expected exception and you can't use an annotation to trap it, you need to catch it and assert that you've got what you expected. For example:

    Throwable caught = null;
    try {
       somethingThatThrows();
    } catch (Throwable t) {
       caught = t;
    }
    assertNotNull(caught);
    assertSame(FooException.class, caught.getClass());
    

    If you can use an annotation instead, do that as it's much clearer. But that's not always possible (e.g., because you're testing a sequence of methods or because you're using JUnit 3).

提交回复
热议问题