为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 JUnit 设置全局规则

如何使用 JUnit 设置全局规则

www说 2021-09-15 16:04:34
我尝试在测试中执行多个断言,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 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

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

}


查看完整回答
反对 回复 2021-09-15
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

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


查看完整回答
反对 回复 2021-09-15
  • 2 回答
  • 0 关注
  • 261 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信