Eclipse's CodePro generates JUnit tests, however, all test methods that it generates throw Exception
even if it is impossible for a checked exception to be thrown. Is this a limitation of CodePro, or a good JUnit practice I haven't seen before?
For example:
@Test
public void testCategory_1()
throws Exception {
String categoryName = "";
Category result = new Category(categoryName);
// add additional test code here
assertNotNull(result);
assertEquals(null, result.getCategoryName());
}
Where new Category(String)
and result.getCategoryName()
don't throw any checked exceptions.
In the case above, you can remove the throws Exception with no problems. However, in the case where you do have an checked Exception, the code becomes much simpler to manage if you just add the throws Exception. Look at the alternative:
as opposed to:
JUnit handles Exceptions exactly the same as assertion failures (which is actually implemented as an AssertionError), so if there is an unexpected exception in your code it will result in a failed test, which is probably what you want. And your test is much clearer
If you have an expected exception, then you can either specify it as expectedException in the @Test annotation or using a
TestRule
ExpectedException.I use this a lot when I have checked exceptions in my code. It's a lot easier to add
throws Exception
to your test method rather than a list of all of the checked Exceptions. You do fall foul of some checkstyle rules though :-)Good practice? Rather acceptable practice. It makes maintenance of tests a lot easier, and the code slightly clearer.