2013-11-26 141 views
2

請考慮使用此測試類,如果運行主過程不會在5分鐘內完成,如果運行測試,則立即成功。有沒有推薦的方法來驗證Executor行爲?我希望測試也能在5分鐘內完成。使用線程進行JUnit測試 - 測試執行程序行爲

我所遇到的具體問題是,創造一個ScheduledExecutorService通過Executors.html#newScheduledThreadPool(int),調度未來,然後取消,今後將不會終止底層Executor作爲默認RemoveOnCancelPolicy是等待取消未來終止之前被調度。我正在通過公開使用ScheduledThreadPoolExecutor來解決此問題,但我希望將此封裝在我的實現中。

public class TestExecutor { 

    @Test public void executorThatIsNotShutdown() { 
     main(null); 
    } 

    public static void main(final String[] args) { 
     final ScheduledExecutorService ex = Executors.newScheduledThreadPool(1); 
     ex.schedule(new Runnable() { 
      @Override 
      public void run() { 
      } 
     }, 5, TimeUnit.MINUTES); 
     ex.shutdown(); 
     System.out.println(ex.toString()); 
    } 
} 

回答

0

你需要添加下面的代碼,使您的主線程等待一段時間,直到你Executorsthread完成其操作

public static void main(final String[] args) { 
    final ScheduledExecutorService ex = Executors.newScheduledThreadPool(1); 
    ex.schedule(new Runnable() { 
     @Override 
     public void run() { 
     } 
    }, 5, TimeUnit.MINUTES); 
    System.out.println(ex.toString()); 
    Thread.sleep('enter the time duration , so that your executor will finish its operation'); 
} 

編輯: - 你可以嘗試的另一種方式。 我也同樣的問題,我已經把Thread.sleep()方法的實際測試方法之前

@Before (method) 
Thread.sleep(mill secs); 
2

嘗試submiting /調度測試方法您的任務後,使用此代碼:

executorService.shutdown(); 
executorService.awaitTermination(5, TimeUnit.MINUTES); 

所以測試線程將被阻塞,直到所有任務完成執行或超時發生爲止

+0

我在等待執行程序終止時並不感興趣,我試圖測試它是否有效。這是非常困難的,因爲JUnit跑步者似乎爲我殺死了Executor。 –