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:
publicvoidtestFoo(){try{doSomething();fail("should have thrown an exception");}catch(Exceptione){}}publicvoidtestFoo2(){try{doSomething();}catch(Exceptione){return;}fail("should have thrown an exception");}publicvoidtestFoo3(){try{doSomething();}catch(Exceptione){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
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
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:
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:
But after reading through the source code, I found out that there already is a
JUnitUseExpectedRule
. It is however in thenet.sourceforge.pmd.lang.java.rule.migrating
package and not included in thejunit.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