May 9, 2011

JUnit test exception handling fail

2  comments

I just found this peace of code in a big java project i’m working on:

public void testSomething() throws IOException
{
    ...

    catch (Exception e)
    {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        fail(sw.toString());
    }
}

Wtf? I changed it to:

public void testSomething() throws IOException
{
    ...

    catch (Exception e)
    {
        fail(e.getMessage());
    }
}

Tags

exception handling, Java, Junit, wtf


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked

Information about Data protection

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. The stacktrace gets lost with your modification. Imho, the best alternative would be to not catch the exception at all and change the throws clause of the method accordingly.

  2. Hey Stefan,
    thanks for your reply. You are right. I have to say that in this case the stack trace was not very use full.

    Anyway with JUnit4 the @Text(expected = MyException.class) annotation makes live much easier.

    Jens

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}