2017-09-24 42 views
1

如何對執行程序服務中運行的代碼進行單元測試? 在我的情況,如何對執行程序服務中運行的代碼片段進行單元測試,而不是等待Thread.sleep(時間)

public void test() { 
    Runnable R = new Runnable() { 
     @Override 
     public void run() { 
      executeTask1(); 
      executeTask2(); 
     } 
    }; 

    ExecutorService executorService = Executors.newSingleThreadExecutor(); 
    executorService.submit(R); 
} 

當我的單元測試,我想提出一些驗證該方法執行。

我在執行程序服務中執行此操作,因爲它執行一些網絡操作。

在我的單元測試中,我必須等到這個方法結束執行。有沒有更好的方式可以做到這一點,而不是等待Thread.sleep(500)

單元測試代碼片段:

@Test 
public void testingTask() { 
    mTestObject.test(); 
    final long threadSleepTime = 10000L; 
    Thread.sleep(threadSleepTime); 
    verify(abc, times(2)) 
      .acquireClient(a, b, c); 
    verify(abd, times(1)).addCallback(callback); 
} 

注:我傳遞一個執行服務對象到這個構造函數的類。 我想知道是否有一種很好的測試方式,而不是等待睡眠時間。

回答

1

有幾個選項:

  • 提取代碼出了執行服務並對其進行測試「獨立」,即在你的榜樣測試executeTask1()executeTask2()自己或連在了一起,但只是沒有被執行他們在一個單獨的線程。你是「路過的執行服務對象到這個構造函數類」,這有助於在這裏,因爲你可以有

    • 它嘲笑執行服務,並驗證您提交的正確運行的吧
    • 測試(測試s),它們驗證executeTask1()executeTask2()的行爲,而不在單獨的線程中運行它們。
  • 使用CountDownLatch允許您的代碼執行器服務在完成時向測試線程指示。例如:

    // this will be initialised and passed into the task which is run by the ExecutorService 
    // and will be decremented by that task on completion 
    private CountDownLatch countdownLatch; 
    
    @Test(timeout = 1000) // just in case the latch is never decremented 
    public void aTest() { 
        // run your test 
    
        // wait for completion 
        countdownLatch.await(); 
    
        // assert 
        // ... 
    } 
    
  • 接受,你必須等待另一個線程來完成,並通過使用Awaitility隱藏在你的測試用例Thread.sleep電話醜陋。例如:

    @Test 
    public void aTest() { 
        // run your test 
    
        // wait for completion 
        await().atMost(1, SECONDS).until(taskHasCompleted()); 
    
        // assert 
        // ... 
    } 
    
    private Callable<Boolean> taskHasCompleted() { 
        return new Callable<Boolean>() { 
         public Boolean call() throws Exception { 
          // return true if your condition has been met 
          return ...; 
         } 
        }; 
    } 
    
+0

但要注意,我的方法,這裏說executeTask1()和executeTask2(),這裏是私人的方法和他們沒有任何返回類型。我沒有找到這種可靠的測試方式。你能建議爲什麼這是可靠的方式嗎? –

+0

我不認爲我可以在沒有看到它們的實現的情況下爲'executeTask1()'和'executeTask2()'測試的細節提供很多幫助。我不認爲我可以提供任何幫助:「我沒有找到這種測試可靠的方式」,而沒有看到你迄今爲止嘗試過的。如果您正在嘗試修改代碼以便從我的答案中選擇選項1或選項2,那麼可能會提供一個解決特定問題並提供[MCVE](https://stackoverflow.com/help/mcve)的單獨問題? – glytching

相關問題