Skip to content
Jens Jäger

JUnit test exception handling fail

This post is part of the archive. It was written years ago, so some of the tools, versions and links may be outdated.

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());
    }
}

2 comments

  1. Stefan

    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.

    1. JensAuthor

      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

Comments are closed. Join the conversation on LinkedIn.