如何使用 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();在每个测试类中都写了。


www说
浏览 262回答 2
2回答

慕尼黑8549860

创建一个抽象类,将 ErrorCollector 放入其中,并使您的所有测试类都扩展此抽象类。public abstract class UnitTestErrorController {&nbsp; &nbsp; // Abstract class which has the rule.&nbsp; &nbsp; @Rule&nbsp; &nbsp; public ErrorCollector collector = new ErrorCollector();}public class CelebrityTest extends UnitTestErrorController {&nbsp; &nbsp; // Whenever a failed test takes places, ErrorCollector handle it.}public class NormalPeopleTest extends UnitTestErrorController {&nbsp; &nbsp; // Whenever a failed test takes places, ErrorCollector handle it.}

肥皂起泡泡

为什么不将“testSetCelebrities”分成多个测试?类似“directorsHasProperSize”、“writersHasProperSize”等。如果您的测试与提供的示例相似,则您似乎正在使用 ErrorCollector 来减少您拥有的测试数量和/或保持它们的名称与它们的方法相似重新测试。这不是必需的,它对您不利,因为您不必要地增加了测试的复杂性,并且您的行比常规断言更难阅读。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java