我尝试在测试中执行多个断言,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();

最佳答案

创建一个抽象类,将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.
}

10-06 06:07