考虑这段代码
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()
已在其他地方进行了测试,我该如何测试此代码?
我很困惑,因为我现在正在学习多线程编程
谢谢
最佳答案
你可以尝试这样测试
public class TestMultiThread {
@Test
public void testThread(){
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new ReportSenderRunnable());
System.out.println("started Report Sender Job");
}
}
关于java - 如何对可运行类进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640297/