Search code examples
javajunitcheckstyle

How to ignore CheckStyle warning for missing @throws for test method?


I'm being plagued by CheckStyle warnings about missing @throws in the JavaDoc of test methods.

I'm using writing a test method like this:

/**
 * Check that something works. <== CheckStyle wants @throws here
 */
@Test
public void testSomething() throws Exception {
  ...
}

Is there a configurable way to tell CheckStyle to ignore this ?

The "throws" clause is there especially because it is a test method; where typically exception handling is ignored.


Solution

  • Yes. You can specify a suppression filter for checkstyle errors for particular files. See Checkstyle 5.5, section SuppressionFilter. From there,

    Filter SuppressionFilter rejects audit events for Check errors according to a suppressions XML document in a file. If there is no configured suppressions file, the Filter accepts all audit events.

    <module name="SuppressionFilter">
        <property name="file" value="docs/suppressions.xml"/>
    </module>
    

    A suppressions XML document contains a set of suppress elements, where each suppress element can have the following attributes:

    • files - a regular expression matched against the file name associated with an audit event. It is mandatory.
    • checks - a regular expression matched against the name of the check associated with an audit event. Optional if id is specified.
    • id - a string matched against the id of the check associated with an audit event. Optional if checks is specified.
    • lines - a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. It is optional.
    • columns - a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. It is optional.

    Each audit event is checked against each suppress element. It is suppressed if all specified attributes match against the audit event.

    So in your case, you could do something like:

    <suppressions>
       <suppress checks="JavadocStyleCheck" files="*Test.java"/>
    </suppressions>
    

    I'm not sure if JavadocStyleCheck is really the check you want to remove, but look in the documentation for more.