Is it against best practice to throw Exception on most JUnit tests?

In general, if you are testing a case where you do not expect an Exception to occur, then I would just let the test method throw Exception as you have illustrated since it will nicely differentiate between Failing test cases (they do not pass one of your assertions) and Error test cases (they cause an unexpected Exception). The JUnit TestRunners will catch the thrown Exception regardless so you don’t have to worry about your entire test suite bailing out if an Exception is thrown.

On the other hand, if you are writing a test that is supposed to trigger an exception, then you either want to use the @Test(expected=IllegalArgumentException.class) variant of the JUnit 4 annotation, or the more common JUnit 3 idiom of:

try {
  target.someMethodToTest();
  fail("Should have gotten an exception");
} catch (IllegalStateException ise) {
  //expected, it's all good
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)