Why does CodePro junit test methods throw Exception (in Eclipse)?

625 views Asked by At

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.

3

There are 3 answers

0
Matthew Farwell On BEST ANSWER

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:

@Test public static void testIt() {
    try {
        foobar(); // throws an IOException
    } catch (Exception e) {
        fail("caught an exception " + e.getMessage());
    }
}

as opposed to:

@Test public static void testIt() throws IOException {
    foobar();
}

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.

0
ditkin On

You don't have to throw Exception, and I would imaging that tool could have performed the static analysis to determine if a checked exception could have been thrown. However, when I write unit tests by hand I typically add the throw clause because invariably I add a line of code that does throw a checked exception.

0
Sri Sankaran On

It definitely is not a limitation. When you write a unit test you don't really care what kind of exception is thrown. Outside of expected exceptions, any exception will result in a red bar telling you that something is not OK. Therefore it is sufficient to have a "catch all" throws Exception clause.