6.6.05

Intentionally failing JUnit tests

In the JUnit mailing list, I followed a discussion about how to implement tests that are failing intentionally with an exception, i.e. the existence of an exception is seen as correct and the other case is a failed test.
Several proposals were made. Let me cite the initial comment on the subject partially:

--------------- snip
Someone in our team writes his tests like this:

try
{
articleProvider.findArticleById("foobar");
}
catch(NoObjectFoundException e)
{
assertTrue(true);
}

He says that e does it because otherwise Checkstyle would complain about the empty catch block.
I do it in this manner:

try
{
articleProvider.findArticleById("foobar");
}
catch(NoObjectFoundException e)
{
// Its okay since we expect it.
}

--------------- snap

I find the "assertTrue(true)" in the catch statement very funny (who codes like this?). It is of course legitimate and correct to take care of Checkstyle, but in this way?

Most (serious) developers in the JUnit mailing list proposed to do it the latter way (putting a comment like //ignore in the catch block), but then you again will get a Checkstyle violation.

What about my solution:
try {
   articleProvider.findArticleById("foobar"); 
catch(NoObjectFoundException e) { 
   ;// this is OK
}
The only simple thing I do is adding a semicolon to the catch block.
Semicolon itself is an empty statement, there you go...
See JGAP for a sample application.

1 comment:

Tom Copeland said...

PMD has a thingy to skip warnings; it works like this:

try {
...
} catch (FooException fe) {} // NOPMD

That way you don't have a gratuitous semicolon in there.