问题
The application is throwing 2 different exceptions in some thatMethod(). I'm looking to test it by JUnit.
I can use ExpectedException and @Rule to set aside a "natural" exception the application is expected to throw. How do you assert that a certain exception is thrown in JUnit 4 tests? is explaining this.
How can i do that in my case-- 2 or more "natural" exceptions? ExpectedException is not holding multiple expected exceptions.
There are other ways to do this-- as explained in How do you assert that a certain exception is thrown in JUnit 4 tests? again. i'm wondering whether there is a way to do this by using the built-in features of JUnit.
回答1:
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.
回答2:
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.
回答3:
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);
}
}
来源:https://stackoverflow.com/questions/20136405/multiple-expected-exceptions-in-junit