java - 如何使用 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();
在每个测试课上都写。
解决方案
创建一个抽象类,放入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.
}
推荐阅读
- sqlite - SQLite 杂注重置为默认值
- html - HTML 图像标签 – 属性宽度/高度和 srcset
- r - 生成小于列值的随机数
- angular - 如何与ngrx一起创建或删除多个数据?
- mongodb - 如何在 MongoDB 中显示匹配特定条件的记录?
- solr - Apache Solr:数据导入处理程序异常 - 在资源中找不到“gs”运算符的 SetGraphicsStateParameters 名称:/R7
- xcode - 如何使用 fastlane 将 .ipa 文件分发到 TestFlight
- c - CS50:我无法打开我的图像恢复程序创建的 JPG
- javascript - JS/ES6:使用过滤器对象过滤数组
- css - mat-icon css 颜色样式不适用