Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何对包含可完成未来的方法进行单元测试?_Java_Unit Testing - Fatal编程技术网

Java 如何对包含可完成未来的方法进行单元测试?

Java 如何对包含可完成未来的方法进行单元测试?,java,unit-testing,Java,Unit Testing,我试着查找这个,但不能完全理解我找到的例子。我有一个类,它有一个SpringAfterPropertiesSet()方法,调用另外两个方法来派生异步调用。我不知道如何对它们进行单元测试。方法startProcessingThread()如下所示: void startProcessingThread(executor) { CompletableFuture.runAsync(() -> { Path filePath = null;

我试着查找这个,但不能完全理解我找到的例子。我有一个类,它有一个Spring
AfterPropertiesSet()
方法,调用另外两个方法来派生异步调用。我不知道如何对它们进行单元测试。方法
startProcessingThread()
如下所示:

void startProcessingThread(executor) {
    CompletableFuture.runAsync(() -> {
        Path filePath = null;       
        do {
            filePath = retrieveFromFileQueue();
            submitFileForProcessing(filePath);            
        } while (keepRunning);
    }, executor)
    .handle((theVoid, exception) -> {           
        if (exception != null) {
            LOG.error("Error submitting file for processing: " + exception);            
        }
        return null;
    });
}

我不想在测试方法中重写
CompletableFuture
(是吗?)。所以我想我需要调用
startProcessingThread()
,在需要它们的方法中使用mock(来自Mockito)(
retrieveFromFileQueue()
submitFileForProcessing()
)。但是,
可完成的未来
本身呢?我应该嘲笑吗?很抱歉,我真的很困惑…

你应该在测试中避免非确定性逻辑,因此我建议避免睡眠。相反,您可以使用Mockito的“when”而不是“verify”,并等待操作执行:

final xyz[] result = new[]{null};
final CountDownLatch latch = new CountDownLatch(1);
when(submitFileForProcessing(...).thenAnswer((Answer<Lwm2mCommand>) invocationOnMock ->
{
    result[0] = invocationOnMock.getArgument(index); // if you need to check the values passed to your method call

    latch.countDown();
}

// Call your method
        assertTrue(latch.await(60L, TimeUnit.SECONDS));
// If needed check the parameters passed to the mocked method
final xyz[]result=new[]{null};
最终倒计时闩锁=新倒计时闩锁(1);
当(提交文件进行处理(…)时。然后应答((应答)调用锁定->
{
结果[0]=invocationMock.getArgument(index);//如果需要检查传递给方法调用的值
倒计时();
}
//调用你的方法
assertTrue(闩锁等待(60L,时间单位秒));
//如果需要,检查传递给模拟方法的参数

还有一个提示:我不会模拟测试中的实际类,而是模拟使用的一个依赖项。

此代码不会等待
CompletableFutur
完成,也不会使用它的结果。为什么选择它而不是普通的
Runnable
?您应该用不同的方法创建lambda(或者作为它自己的类),然后您可以模拟它并检查此方法是否运行它(让您的测试在调用该方法后等待几毫秒),你也可以直接验证lambdas行为本身。Timothy,这段代码不是我设计的。我真的不知道为什么要使用CompletableFuture。它与Runnable相比没有任何优势吗,就像它目前使用的方式一样??另外,我们决定不想在单元测试方法中设置睡眠。所以现在我们只想在Integral期间测试它定量。“我们决定我们不想让单元测试方法陷入休眠状态。”随着我的改变,我建议最终的方法将是“简单到失败”,因此不进行单元测试是没有风险的,但你仍然可以理解可实现/可完成未来的逻辑。