2016-11-30 21 views
0

我在我的代碼中實現了一個TimerTask。它會定期對應用程序邏輯進行一些修改。現在我想用JUnit測試這個TimerTask的影響。假設TimerTask計劃每2秒運行一次,但我應該運行測試用例而不使用Thread.sleep。JUnit測試沒有使用Thread.sleep的預定影響邏輯

public class LogService { 

    public LogService() { 
     configuration = ConfigurationUtil.getConfgiration(); 
     Timer timer = new Timer(true); 
     timer.scheduleAtFixedRate(new ScheduledAgent(), 0, configuration.getWaitTime()); 
    } 

    private List<LoggingDetails> loggingDetails; 

    public List<LoggingDetails> getLoggers() { 
     return loggingDetails; 

    } 

    class ScheduledAgent extends TimerTask { 

     @Override 
     public void run() { 
      // if time has taken more than wait time, then clear loggingDetails 

     } 
    } 
} 

一個單元測試場景是我在waitTime時間段內得到loggingDetails。這是可以實現的。另一種情況是,我應該測試並確認在等待時間後,列表被清除併爲空。

+1

我認爲我們需要更多關於你的需求的細節,但你可能想看看[JMockit](http://jmockit.org),我認爲它可以讓你模擬一些像Thread.sleep這樣的系統方法,或者返回當前時間的方法。 – ajb

回答

1

在你的情況下,我會分開單元測試LogServiceScheduledAgent

因此,您將實現可以測試ScheduledAgent的實際邏輯。

另一種情況是,在你的測試LogService你必須檢查scheduleAtFixedRate方法是調用正確的參數。爲此,您可以使用一些庫,如JMockitPowerMockito。很可能你需要將timer作爲該類的一個領域來實現嘲笑它的可能性。從我的角度來看,您不需要測試scheduleAtFixedRate方法定期調用提供的TimerTask,因爲此方法來自JDK,並且肯定已經由成千上萬的開發人員進行測試。