如何为该异步方法编写单元测试?

时间:2020-08-06 03:14:46

标签: java multithreading unit-testing asynchronous mockito

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

经过测试的代码如下:

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);
}

需要模拟的方法如下:

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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