【问题标题】:How do I Unit Test Runnable Class?如何对可运行类进行单元测试?
【发布时间】:2015-04-15 01:55:48
【问题描述】:

考虑到这段代码

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() 已经在其他地方进行了测试,我该如何测试这段代码?

我很困惑,因为我现在正在学习多线程编程

谢谢

【问题讨论】:

  • new ReportSenderRunnable().run()?
  • @Lashane,我正在寻找JUnit 测试多线程代码的方式
  • @daydreamer 我想知道多线程测试是否合适。你要测试的只是run()中的逻辑,不需要多线程测试

标签: java multithreading concurrency java.util.concurrent


【解决方案1】:

你可以试试这样测试

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

【讨论】:

  • 当我已经通过新的 Runnable 时,我不确定如何测试我的代码
  • 你可以像你的代码一样使用executorService.execute(new ReportSenderRunnable());
猜你喜欢
  • 2011-09-17
  • 2011-12-19
  • 2014-10-08
  • 2011-03-24
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 2020-05-21
相关资源
最近更新 更多