【问题标题】:How to Cover code written inside taskExecutor.execute(new Runnable..) using junit5如何使用 junit5 覆盖 taskExecutor.execute(new Runnable..) 中编写的代码
【发布时间】:2021-02-12 09:40:17
【问题描述】:

想为execute方法中的代码编写junit5测试用例/覆盖如下是我的示例(虚拟)src类,实际方法包含项目大量业务逻辑。

如果我模拟 taskExecutor,它会使用虚拟值绕过整个 execute()。

任何建议我如何在附加代码中覆盖运行方法,下面是示例测试用例

【问题讨论】:

标签: java spring spring-boot junit junit5


【解决方案1】:

您可以将您的内联 Runnable 外包给它自己的类,例如:

public class MyRunnable implements Runnable {

  private final JdbcTemplate jdbcTemplate;

  public MyRunnable(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public void run() {
    // ... do your logic here
  }
}

然后为这个类编写一个单元测试来单独验证它的行为。

在您的RedisScheduler 中,您可以使用您的新类:

taskExecutor.execute(new MyRunnable(jdbcTemplate));

【讨论】:

  • 解决方案看起来不错,但代码正在生产中,因此由于 junit 测试用例,他们不允许我更改任何源代码。有没有办法在不改变来源的情况下实现这一目标?
猜你喜欢
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多