【问题标题】:How can I write a unit test for this asynchronous method?如何为这种异步方法编写单元测试?
【发布时间】:2020-08-06 03:14:46
【问题描述】:

当我为业务代码编写单元测试时,我需要模拟异步线程调用并返回模拟结果保存在数据库中。我不知道如何为这个方法编写单元测试代码。

测试代码如下:

public void doWork(){
        ExecutorService executor = Executors.newSingleThreadExecutor();
        FutureTask<TestVO> futureResult = null;

        futureResult = new FutureTask<TestVO>(new Callable<TestVO>() {
                public TestVO call() {
                    return testService.scan(_scan_params, finalProcess, _ywid, _logPath);
                }
            });

       executor.execute(futureResult);
       TestVO testVO = futureResult.get(0, TimeUnit.SECONDS);
       TestRepository.save(testVO);
}

需要mock的方法如下:

@Async("taskAccStepExecutor")
public TestVO scan(String params, String process, String ywid, String LogPath) {
       ......
       return testVO;
}

我在项目中使用 testng/mokito 作为测试框架。

我的期望是模拟一个异步线程并返回一个自定义的 testVO。这个问题困扰了我好几天,希望能得到您的帮助。

【问题讨论】:

    标签: java multithreading unit-testing asynchronous mockito


    【解决方案1】:

    假设定义 doWork() 方法的类(我们称其为“Worker”类)以某种方式注入了“testService”,并且您可以控制它的注入方式。

    在这种情况下,如果您在单元测试中创建一个带有模拟 testService 的 Worker 就足够了。添加 when(testService.scan(anyString(), anyString(), anyString(), anyString()).thenReturn(new TestVO()) 以模拟您对服务的期望。 然后调用 doWork 方法,因为这似乎是您要测试的方法。 然后验证是否调用了扫描方法:verify(testService).scan(anyString(), anyString(), anyString(), anyString())。 也许还可以验证 TestVO 对象是否已保存到您的数据库中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      相关资源
      最近更新 更多