首页 > 解决方案 > 如何使用 JUnit 设置全局规则

问题描述

我尝试在测试中执行多个断言,JUnit 在第一个失败的断言处停止。

因此,为了能够执行所有断言并在最后列出失败的断言,我使用了类ErrorCollector和 JUnit 的@Rule注释。
下面是一个测试类的例子:

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));
    }
}

现在我有另一个类,它的方法有多个断言。有什么办法可以使@Rule通用,所以我不必public ErrorCollector collector = new ErrorCollector();在每个测试课上都写。

标签: javaunit-testingjunit

解决方案


创建一个抽象类,放入ErrorCollector,让你所有的测试类扩展这个抽象类。

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.
}

推荐阅读