如何使用JUnit

时间:2018-09-12 17:32:03

标签: java unit-testing 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();

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

为什么不只是将“ testSetCelebrities”分成多个测试?如“ directorHasProperSize”,“ writersHasProperSize”等。如果您的测试与所提供的示例相似,则似乎您正在使用ErrorCollector减少所拥有的测试数量和/或使其名称与所使用的方法相似。重新测试。这是没有必要的,并且对您不利,因为您不必要地增加了测试的复杂性,并且比常规的断言更难读取行。