考虑到这一代码单元测试可运行类如何?
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()'中的逻辑,你不需要让它测试多线程 –