考慮到這一代碼單元測試可運行類如何?
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()
已經測試了別的地方,我怎麼能測試該代碼?
我很很困惑,因爲我學習多線程編程現在
謝謝
'新ReportSenderRunnable()。運行() '? –
@Lashane,我期待'JUnit'測試多線程代碼的方式 – daydreamer
@daydreamer我不知道測試它是否合適多線程。你應該測試的只是'run()'中的邏輯,你不需要讓它測試多線程 –