Multiple expected exceptions in JUnit

守給你的承諾、 提交于 2019-12-05 17:24:59

A single test method can only exit once, and so can only throw a single exception. If you wish to confirm that your code can fail in two different ways then you have two separate tests; split it into two test methods and declare the specific exception on each.

You can collect multiple exceptions with ErrorCollector and verify them at the end of the test. But you have to add the exceptions to the collector manually, because JUnit sees only your test method and cannot do anything during method execution.

I found this way because JUnit functions accepts only one exception.

@Test
public void checkRuleValidation() {
    Rule rule = generateRules(1, "rule.json").get(0);
    // rule name validation
    rule.setRuleName(null);
    try {
        ruleResource.saveRule(rule);
        // expecting exception if no assert false
        assertTrue(false);
    } catch (BadRequestException br) {
        assertTrue(true);
    }

    //validating rule action
    rule.setRuleAction(null);
    try {
        ruleResource.saveRule(rule);
        // expecting exception if no assert false
        assertTrue(false);
    } catch (AuthorizationException br) {
        assertTrue(true);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!