2017-04-05 30 views
0

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

StopWatch是抽象的,但它沒有任何抽象方法,這樣你就不會需要重寫所有的人,但你仍然有實例化一個匿名類,這是稍微不太麻煩:

@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); 
    } 
}; 
+0

謝謝!但是如果我想實現一個自定義的StopWatch註解 - MyStopWatch,並且直接在需求上面使用它的測試方法,就像'@ Test'' @ Before'可以'junit'通過實現一些類來支持它嗎? – zhuguowei

+0

@zhuguowei這是可能的。我想你需要實現自定義[test runner](https://github.com/junit-team/junit4/wiki/Test-runners) –

相關問題