In our Software Quality and Testing course at the TU Delft, students often come up with very creative (and often faulty) ways of asserting exceptions. In JUnit it is prefered to use the expected attribute of the Test annotation, or the ExpectedException TestRule implementation.

Some implementations we see:

 public void testFoo() {
     try {
         doSomething();
         fail("should have thrown an exception");
     } catch (Exception e) {
     }
}

 public void testFoo2() {
     try {
         doSomething(); 
     } catch (Exception e) {
         return;
     }
     fail("should have thrown an exception");
}

 public void testFoo3() {
     try {
         doSomething(); 
     } catch (Exception e) {
         assertTrue(true);
     }
}

I think, in fact, any Catch statement in a Test method makes no sense, as you one want a single execution path through your test method. Therefore I came up with the following XPath expression:

//CatchStatement
[ancestor::ClassOrInterfaceDeclaration[//ClassOrInterfaceType[typeof(@Image, 'junit.framework.TestCase','TestCase')] or //MarkerAnnotation/Name[typeof(@Image, 'org.junit.Test', 'Test')]]]

But after reading through the source code, I found out that there already is a JUnitUseExpectedRule. It is however in the net.sourceforge.pmd.lang.java.rule.migrating package and not included in the junit.xml file. Why is this? Is it waiting to be converted to an XPath expression? And would such a PR be merged?

 

Last edit: Jan-Willem Gmelig Meyling 2016-02-28