public class RequireFailForTryCatchInJunitCheck
extends com.puppycrawl.tools.checkstyle.api.AbstractCheck
Checks if a try/catch block has a fail assertion at the end of a try block in a JUnit test method.
Rationale: Tests should not complete the try block naturally if they are expecting a failure. If the try completes normally the test will pass successfully and skip over any assertions in the catch block. If tests are not expecting exceptions, then they should remove the catch block and propagate the exception to the JUnit caller which will display the full exception to the user.
A JUnit test method is identified by the annotations placed on it. It is only considered a JUnit method if it contains the annotation 'org.junit.Test'. This check doesn't examine methods called by a test method. It must contain the annotation. Failures are identified by a method call to either:
An example of how to configure the check is:
<module name="RequireFailForTryCatchInJunitCheck"/>
which will cause a violation in the example below:
@Test
public void testMyCase() {
try { // <-- violation here because try block misses fail assertion.
verifySomeResult(); // <-- add e.g. 'Assert.fail()' after this last statement
// of the try block to resolve the violation
}
catch (IllegalArgumentException ex) {
assertEquals("expected exception message",
"Some message that is expected", ex.getMessage());
}
}
| Modifier and Type | Field and Description |
|---|---|
static String |
MSG_KEY
Violation message key.
|
| Constructor and Description |
|---|
RequireFailForTryCatchInJunitCheck() |
| Modifier and Type | Method and Description |
|---|---|
void |
beginTree(com.puppycrawl.tools.checkstyle.api.DetailAST rootAST) |
int[] |
getAcceptableTokens() |
int[] |
getDefaultTokens() |
int[] |
getRequiredTokens() |
void |
visitToken(com.puppycrawl.tools.checkstyle.api.DetailAST ast) |
clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeveritypublic static final String MSG_KEY
public int[] getDefaultTokens()
getDefaultTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic int[] getAcceptableTokens()
getAcceptableTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic int[] getRequiredTokens()
getRequiredTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic void beginTree(com.puppycrawl.tools.checkstyle.api.DetailAST rootAST)
beginTree in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic void visitToken(com.puppycrawl.tools.checkstyle.api.DetailAST ast)
visitToken in class com.puppycrawl.tools.checkstyle.api.AbstractCheckCopyright © 2021. All rights reserved.