CodeNarc - CodeNarc - JUnit Rules

##### General

- Home
- Downloads
- Road Map
- Javadocs
- Mailing Lists
- Bug Tracker
- SourceForge Project

##### Running

- Ant Task Usage
- Command-Line
- Run as a Test
- Other Tools/Frameworks

##### Using

- Creating a RuleSet
- Creating a Rule
- Configuring Rules
- Starter RuleSet (All)

##### Report Types

- HTML (HtmlReportWriter)
- XML (XmlReportWriter)
- Text (TextReportWriter)

##### Sample Reports

- Sample HTML Report
- Open Source Projects

##### Rules

- Rule Index
- Basic Rules
- Braces Rules
- Concurrency Rules
- Convention Rules
- Design Rules
- DRY Rules
- Exceptions Rules
- Formatting Rules
- Generic Rules
- Grails Rules
- Groovyism Rules
- Imports Rules
- JDBC Rules
- JUnit Rules
- Logging Rules
- Naming Rules
- Size/Complexity Rules
- Security Rules
- Serialization Rules
- Unnecessary Rules
- Unused Rules

##### Developing

- Developer Guide

##### Project Documentation

- Project Information
- Project Reports

## JUnit Rules ("rulesets/junit.xml")

### ChainedTest Rule

New in CodeNarc 0.13

A test method that invokes another test method is a chained test; the methods are dependent on one another. Tests should be isolated, and not be dependent on one another.

Example of violations:

        class MyTest extends GroovyTestCase {
            public void testFoo() {

                // violations, calls test method on self
                5.times { testBar() }
                5.times { this.testBar() }

                // OK, no violation: one arg method is not actually a test method
                5.times { testBar(it) }
            }

            private static void assertSomething() {
                testBar() // violation, even if in helper method
                this.testBar() // violation, even if in helper method
            }

            public void testBar() {
                // ...
            }
        }

### CoupledTestCase Rule

New in CodeNarc 0.13

This rule finds test cases that are coupled to other test cases, either by invoking static methods on another test case or by creating instances of another test case. If you require shared logic in test cases then extract that logic to a new class where it can properly be reused.

Example of violations:

        class MyTest extends GroovyTestCase {
            public void testMethod() {
                // violation, static method call to other test
                MyOtherTest.helperMethod()

                // violation, instantiation of another test class
                new MyOtherTest()
            }
        }

### JUnitAssertAlwaysFails Rule

Rule that checks for JUnit `assert()` method calls with constant arguments such that the assertion always fails. This includes: `assertTrue(false)`, `assertFalse(true)` and `assertNull(CONSTANT)`.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

### JUnitAssertAlwaysSucceeds Rule

Rule that checks for JUnit `assert()` method calls with constant arguments such that the assertion always succeeds. This includes: `assertTrue(true)`, `assertFalse(false)` and `assertNull(null)`.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

### JUnitPublicNonTestMethod Rule

Rule that checks if a JUnit test class contains public methods other than standard test methods, JUnit framework methods or methods with JUnit annotations.

The following public methods are ignored by this rule:

- Zero-argument methods with names starting with "test"
- The `setUp()` and `tearDown()` methods
- Methods annotated with `@Test`
- Methods annotated with `@Before` and `@After`
- Methods annotated with `@BeforeClass` and `@AfterClass`
- Methods annotated with `@Override`

Public, non-test methods on a test class violate conventional usage of test classes, and they typically break encapsulation unnecessarily.

Public, non-test methods may also hide unintentional 'Lost Tests'. For instance, the test method declaration may (unintentionally) include methods parameters, and thus be ignored by JUnit. Or the method may (unintentionally) not follow the "test.." naming convention and not have the @Test annotation, and thus be ignored by JUnit.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

### JUnitSetUpCallsSuper Rule

Rule that checks that if the JUnit `setUp` method is defined, that it includes a call to `super.setUp()`.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

### JUnitStyleAssertions Rule

Since CodeNarc 0.11

This rule detects calling JUnit style assertions like `assertEquals`, `assertTrue`, `assertFalse`, `assertNull`, `assertNotNull`. Groovy 1.7 ships with a feature called the "power assert", which is an assert statement with better error reporting. This is preferable to the JUnit assertions.

### JUnitTearDownCallsSuper Rule

Rule that checks that if the JUnit `tearDown` method is defined, that it includes a call to `super.tearDown()`.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

### JUnitUnnecessarySetUp Rule

Rule that checks checks for JUnit `setUp()` methods that contain only a call to `super.setUp()`. The method is then unnecessary.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

Here is an example of a violation:

        class MyTest extends TestCase {
            void setUp() {              // violation
                super.setUp()
            }
        }

### JUnitUnnecessaryTearDown Rule

Rule that checks checks for JUnit `tearDown()` methods that contain only a call to `super.tearDown()`. The method is then unnecessary.

This rule sets the default value of the applyToClassNames property to only match class names ending in 'Test', 'Tests' or 'TestCase'.

Here is an example of a violation:

        class MyTest extends TestCase {
            void tearDown() {               // violation
                super.tearDown()
            }
        }

### UseAssertEqualsInsteadOfAssertTrue Rule

Since CodeNarc 0.11

This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like `assertEquals`.

### UseAssertFalseInsteadOfNegation Rule

Since CodeNarc 0.12

In unit tests, if a condition is expected to be false then there is no sense using `assertTrue` with the negation operator. For instance, `assertTrue(!condition)` can always be simplified to `assertFalse(condition)`.

### UseAssertTrueInsteadOfAssertEqualsRule Rule

Since CodeNarc 0.11

This rule detects JUnit calling `assertEquals` where the first parameter is a boolean. These assertions should be made by more specific methods, like `assertTrue` or `assertFalse`.

All of the following examples can be simplified to assertTrue or remove the true literal:

        assertEquals(true, foo())
        assertEquals("message", true, foo())
        assert true == foo()
        assert foo() == true : "message"
        assertEquals(foo(), true)
        assertEquals("message", foo(), true)
        assertEquals(false, foo())
        assertEquals("message", false, foo())
        assert false == foo()
        assert foo() == false : "message"
        assertEquals(foo(), false)
        assertEquals("message", foo(), false)

### UseAssertTrueInsteadOfNegation Rule

Since CodeNarc 0.12

In unit tests, if a condition is expected to be true then there is no sense using `assertFalse` with the negation operator. For instance, `assertFalse(!condition)` can always be simplified to `assertTrue(condition)`.

### UseAssertNullInsteadOfAssertEquals Rule

Since CodeNarc 0.11

This rule detects JUnit calling `assertEquals` where the first or second parameter is `null`. These assertion should be made against the `assertNull` method instead.

### UseAssertSameInsteadOfAssertTrue Rule

Since CodeNarc 0.11

This rule detects JUnit calling `assertTrue` or `assertFalse` where the first or second parameter is an `Object#is()` call testing for reference equality. These assertion should be made against the `assertSame` or `assertNotSame` method instead.

### JUnitFailWithoutMessage Rule

Since CodeNarc 0.11

This rule detects JUnit calling the `fail()` method without an argument. For better error reporting you should always provide a message.

### JUnitTestMethodWithoutAssert Rule

Since CodeNarc 0.12

This rule searches for test methods that do not contain assert statements. Either the test method is missing assert statements, which is an error, or the test method contains custom assert statements that do not follow a proper assert naming convention. Test methods are defined as public void methods that begin with the work test or have a @Test annotation. By default this rule applies to the default test class names, but this can be changed using the rule's applyToClassNames property. An assertion is defined as either using the `assert` keyword or invoking a method that starts with the work assert, like assertEquals, assertNull, or assertMyClassIsSimilar. Also, any method named `should.*` also counts as an assertion so that `shouldFail` methods do not trigger an assertion, any method that starts with `fail>> counts as an assertion, and any method that starts with <<<verify` counts as an assertion.

What counts as an assertion method can be overridden using the assertMethodPatterns property of the rule. The default value is this comma separated list of regular expressions:

            String assertMethodPatterns = 'assert.*,should.*,fail.*,verify.*'

If you'd like to add any method starting with 'ensure' to the ignores then you would set the value to this:

        'assert.*,should.*,fail.*,verify.*,ensure.*'

### SpockIgnoreRestUsed Rule

New in CodeNarc 0.14 If Spock's @IgnoreRest appears on any method, all non-annotated test methods are not executed. This behaviour is almost always unintended. It's fine to use @IgnoreRest locally during development, but when committing code, it should be removed.

Example of violations:

        public class MySpec extends spock.lang.Specification {
            @spock.lang.IgnoreRest
            def "my first feature"() {
                expect: false
            }

            def "my second feature"() {
                given: def a = 2

                when: a *= 2

                then: a == 4
            }
        }

### UnnecessaryFail Rule

New in CodeNarc 0.13

In a unit test, catching an exception and immediately calling Assert.fail() is pointless and hides the stack trace. It is better to rethrow the exception or not catch the exception at all.

Example of violations:

        public void testSomething() {
            try {
                something()
            } catch (Exception e) {
                fail(e.message)
            }

            try {
                something()
            } catch (Exception e) {
                fail()
            }
        }