【发布时间】:2015-07-27 23:01:22
【问题描述】:
我的项目中有大约 5000 个单元测试,我正在尝试记录每个单元测试所花费的时间。我无法通过进入每个单元测试来编辑@Before 和@After。
我正在尝试使用@Rule,但不知何故没有帮助,我什至无法让它工作,但我将注释更改为@ClassRule 并使我的观察者静态我能够至少掌握开始和结束单元测试执行,我只是不知道单元测试的名称。这是我的代码:
我有一个名为 IIMUnitTest(父类)的类,所有单元测试都扩展了这个类。
我在 IIMUnitTest 中添加了以下代码
@Rule
public TestRule watcher = new TestWatcher() {
Long timeStart;
protected void starting(Description description) {
timeStart = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
System.out
.println("===========================================================================");
System.out.println("Test: " + description.getMethodName());
TimeZoneFormat dateFormat = null;
System.out.println("Start Time: " + dateFormat.format(cal.getTime()));
System.out
.println("==============================================");
}
protected void finished(Description description) {
Long timeEnd = System.currentTimeMillis();
double seconds = (timeEnd-timeStart)/1000.0;
System.out
.println("\n============================================================");
System.out
.println("Test completed - ran in: "+new DecimalFormat("0.000").format(seconds)+" sec");
System.out
.println("========================\n");
}
};
提前致谢。
【问题讨论】:
-
你在开始和结束测试时是否调用了starting()和finished()?
-
@Fooble:它们是覆盖。 TestWatcher calls them automatically.
-
将
dateFormat设置为 null 以外的值。 -
@DonBottstein 我的错,这确实有效。但它会在每种方法之后进行系统打印。不是在每个单元测试之后(完整类)
-
@NickChh
description.getClassName()会给你正在测试的类的名称,这在使用@ClassRule时更合适:-)。