Testing for multiple exceptions with JUnit 4 annotations

后端 未结 7 2309
-上瘾入骨i
-上瘾入骨i 2020-12-30 22:06

Is it possible to test for multiple exceptions in a single JUnit unit test? I know for a single exception one can use, for example

    @Test(expected=Illega         


        
7条回答
  •  不知归路
    2020-12-30 22:25

    You really want the test to do one thing, and to test for that. If you're not sure as to which exception is going to be thrown, that doesn't sound like a good test to me.

    e.g. (in pseudo-code)

    try {
       badOperation();
       /// looks like we succeeded. Not good! Fail the test
       fail();
    }
    catch (ExpectedException e) {
       // that's fine
    }
    catch (UnexpectedException e) {
       // that's NOT fine. Fail the test
    }
    

    so if you want to test that your method throws 2 different exceptions (for 2 sets of inputs), then you'll need 2 tests.

提交回复
热议问题