Ayoub k
Ayoub k

Reputation: 8868

How to set a global rule with JUnit

I attempt to perform multiple assertions in a test, JUnit stops at the first failed assertion.

So to be able to do all assertions and listing the failed ones at the end, I used the class ErrorCollector and the JUnit’s @Rule annotation.
Here's an example of a test class:

public class MovieResponseTest {

    /**
     * Enable a test not to stop on an error by doing all assertions and listing the failed ones at the end.
     * the <code>@Rule</code> annotation offers a generic way to add extended features on a test method
     */
    @Rule
    public ErrorCollector collector = new ErrorCollector();


    /**
     * A test case for <code>setCelebrity</code> Method
     * @see MovieResponse#setCelebrities(List)
     */
    @Test
    public void testSetCelebrities() {
        // Some code

        this.collector.checkThat("The size of cast list should be 1.", this.movieResponse.getCast(), hasSize(1));
        this.collector.checkThat("The size of directors list should be 1.", this.movieResponse.getDirectors(), hasSize(1));
        this.collector.checkThat("The size of writers list should be 1.", this.movieResponse.getWriters(), hasSize(1));
    }
}

Now i have another class with a method that have multiple assertions. Is there any way to make the @Rule general so i don't have to write public ErrorCollector collector = new ErrorCollector(); in every test class.

Upvotes: 0

Views: 897

Answers (2)

Ekrem Demirhan
Ekrem Demirhan

Reputation: 204

Create an abstract class, put ErrorCollector in it, and make your all test classes extend this abstract class.

public abstract class UnitTestErrorController {
    // Abstract class which has the rule.
    @Rule
    public ErrorCollector collector = new ErrorCollector();

}

public class CelebrityTest extends UnitTestErrorController {
    // Whenever a failed test takes places, ErrorCollector handle it.
}

public class NormalPeopleTest extends UnitTestErrorController {
    // Whenever a failed test takes places, ErrorCollector handle it.
}

Upvotes: 3

thenamethatwasnottaken
thenamethatwasnottaken

Reputation: 166

Why not just separate "testSetCelebrities" into multiple tests? Something like "directorsHasProperSize", "writersHasProperSize", etc. If your tests are similar to the example provided, it seems like you're using ErrorCollector to reduce the number of tests you have and/or keep their names similar to the methods they're testing. That's not necessary and it's working against you, as you're increasing the complexity of your tests unnecessarily and your lines are harder to read than regular asserts.

Upvotes: 0

Related Questions