2016-10-22 57 views
2

這是第一次,我正在嘗試爲多線程java程序編寫JUnit。如何測試創建單獨線程的方法?

我有一個方法,看起來像下面,你能建議我怎麼可以寫的JUnit的呢?或者指出任何這樣的類似例子?非常感謝您提前... !!

public void myMethod(Input input) { 
    if (!this.isStreamingPaused()) { 
     ExecutorService publisherThreadPool = getThreadPool(); 
     PublisherThread publisher = new PublisherThread(); 
     publisher.setInputData(input); 
     publisherThreadPool.execute(publisher); 
     publisherThreadPool.shutdown(); 
    } 
} 

public ExecutorService getThreadPool() { 
     final ThreadFactory threadFactory = new BasicThreadFactory.Builder() 
       .namingPattern("MyName-%d") 
       .priority(Thread.NORM_PRIORITY) 
       .build(); 
     return Executors.newFixedThreadPool(1, threadFactory); 
} 
+1

獨立您的問題。顧名思義,單元測試應該以功能單元爲目標。對產生線程的類進行一次測試,並對線程類本身進行第二次測試。 – EJK

+0

謝謝EJK的回覆。我將在PublisherThread線程中爲主要功能編寫單獨的junit,但是我在這裏擔心如何測試myMethod中生成線程的代碼塊? – user3452558

+0

請注意,像這樣創建線程池意味着您不能多次執行'myMethod'。您可能還想檢查執行程序是否已關閉,並在此情況下創建新實例。 –

回答

1

您可以嘗試使用一個java.util.concurrent.CountDownLatch

public void myMethod(Input input) { 
    if (!this.isStreamingPaused()) { 
     ExecutorService publisherThreadPool = getThreadPool(); 

     // in case that you'd have more of the same kind of operations to do 
     // you can use appropriately a higher count than 1 
     CountDownLatch latch = new CountDownLatch(1); 

     PublisherThread publisher = new PublisherThread(); 
     publisher.setInputData(input); 
     publisherThreadPool.execute(publisher); 
     publisherThreadPool.shutdown(); 


     try { 
      latch.await(); 
     } catch (InterruptedException e) { 
      LOG.info("Interrupted by another thread"); 
     } 
    } 
} 

在你PublisherThread類你做這些改變:

private CountDownLatch latch; 

public PublisherThread(CountDownLatch latch){ 
    this.latch = latch; 
} 

public void run(){ 
    try{ 
     // kafka business logic 
     // .... 
    } finally { 
     // you don't want your program to hang in case of an exception 
     // in your business logic 
     latch.countDown(); 
    } 
}