如何测试执行另一个runnable的runnable

时间:2016-08-01 12:52:43

标签: java multithreading junit

我有一些runnable,其中一个参数是taskManager执行委托,以执行另一个runnable:

@Override
public void run() {
    try {
        doTask(messageId);
    } catch (Exception e) {
        count++;
        if (count < 4) {
            delegatedTransactionalAsyncTaskExecutor.execute(this);
        } else {
            delegatedTransactionalAsyncTaskExecutor.execute(getOnExceedErrorTask(messageId));
        }
        throw new RuntimeException(e);
    }
}

我应该如何测试?

1 个答案:

答案 0 :(得分:1)

似乎delegatedTransactionalAsyncTaskExecutor是您班级中的一个字段。

为了确保您可以测试它,您必须使用依赖注入,如下所示:

class UnderTest {
  private final Whatever delegatedTransactionalAsyncTaskExecutor;
  UnderTest(Whatever delegatedTransactionalAsyncTaskExecutor) {
    this.delegatedTransactionalAsyncTaskExecutor = delegatedTransactionalAsyncTaskExecutor;
  ...

现在,您可以使用模拟框架来创建该Whatever类的对象。模拟允许您指定您希望发生的方法调用;然后,您可以稍后验证这些呼叫是否真的发生了。

换句话说:你准备一个模拟;然后你调用run()...然后你检查你正在寻找的那些调用是否真的发生了。当然,要完成所有工作,你必须能够将这些模拟注入你的“被测试的课堂”。

相关问题