2015-04-15 206 views
1

考慮到這一代碼單元測試可運行類如何?

class ReportSenderRunnable implements Runnable { 

    @Override 
    public void run() { 
     executeTasks(); 
    } 

    private void executeTasks() { 
     try { 
     runTask1(); 
     } catch (final InterruptedException e) { 
     logError(ReportStatus.COMPRESSING, e.getMessage()); 
     reportStatus = ReportStatus.EXCEPTION_IN_COMPRESSION; 
     } catch (final IllegalStateException e) { 
     logError(ReportStatus.COMPRESSING, e.getMessage()); 
     reportStatus = ReportStatus.EXCEPTION_IN_COMPRESSION; 
     } 

     try { 
     reportStatus = ReportStatus.SENDING; 
     runTask2(); 
     } catch (final InterruptedException e) { 
     reportStatus = ReportStatus.EXCEPTION_IN_SENDING; 
     } 

     try { 
     reportStatus = ReportStatus.SUBMITTING_REPORT; 
     runTask3(); 
     } catch (final InterruptedException e) { 
     reportStatus = ReportStatus.EXCEPTION_IN_SUBMITTING_REPORT; 
     } 

     System.out.println("Report Sender completed"); 
     reportStatus = ReportStatus.DONE; 
    } 

    private void logError(final ReportStatus status, final String cause) { 
     LOGGER.error("{} - {}", status, cause); 
    } 
    } 

這段代碼被傳遞到ExecutorService運行。

private void submitJob() { 
    final ExecutorService executorService = Executors.newSingleThreadExecutor(); 
    executorService.execute(new ReportSenderRunnable()); 
    System.out.println("started Report Sender Job"); 
    } 

假設runTask1()runTask2()runTask3()已經測試了別的地方,我怎麼能測試該代碼?

我很很困惑,因爲我學習多線程編程現在

謝謝

+1

'新ReportSenderRunnable()。運行() '? –

+0

@Lashane,我期待'JUnit'測試多線程代碼的方式 – daydreamer

+0

@daydreamer我不知道測試它是否合適多線程。你應該測試的只是'run()'中的邏輯,你不需要讓它測試多線程 –

回答

1

,你可以嘗試測試這樣

public class TestMultiThread { 
@Test 
public void testThread(){ 
    final ExecutorService executorService = Executors.newSingleThreadExecutor(); 
    executorService.execute(new ReportSenderRunnable()); 
    System.out.println("started Report Sender Job"); 
} 
} 
+0

我不知道如何測試我的代碼,當我已經通過一個新的Runnable – daydreamer

+0

你可以只用作你的代碼 executorService.execute(新的ReportSenderRunnable()); –