Junit有一些特殊的注释可以自动计算花费的时间吗?如果是这样,我可以避免手动计算时间,如下所示:
long start = System.currentTimeMillis();
// do something here
long end = System.currentTimeMillis();
log.info("took time: {}", end - start);
assertTrue((end - start) > 1000L);
现在我觉得StopWatch
有点麻烦:
@Rule
public Stopwatch stopwatch = new Stopwatch() {
@Override
protected void succeeded(long nanos, Description description) {
logInfo(description, "succeeded", nanos);
}
@Override
protected void failed(long nanos, Throwable e, Description description) {
logInfo(description, "failed", nanos);
}
@Override
protected void skipped(long nanos, AssumptionViolatedException e, Description description) {
logInfo(description, "skipped", nanos);
}
@Override
protected void finished(long nanos, Description description) {
logInfo(description, "finished", nanos);
}
};
理想情况下,我想要这个效果:
@Test
@StopWatch
public void test_sleep_1_seconds(){
sleep1();
assertTrue(stopwatch.runtime(TimeUnit.SECONDS) > 1L);
}
我如何实施自定义StopWatch
?
答案 0 :(得分:0)
StopWatch是抽象的,但它没有任何抽象方法,因此您不需要覆盖所有这些方法,但是您仍然必须实例化一个匿名类,这稍微不那么麻烦: / p>
@Rule
public Stopwatch stopwatch = new Stopwatch() {};
@Test
public void test_sleep_1_seconds() {
sleep1();
assertTrue(stopwatch.runtime(TimeUnit.SECONDS) > 1);
}
实际上,根据#1110,StopWatch
不需要是抽象的,而是更改为常规类。这些更新将在JUnit 4.13中发布。
如果您需要对所有测试进行检查,可能需要覆盖succeeded
:
@Rule
public Stopwatch stopwatch = new Stopwatch() {
@Override
protected void succeeded(long nanos, Description description) {
assertTrue(runtime(TimeUnit.SECONDS) > 1);
}
};