繁体   English   中英

如何模拟 completablefuture.get()?

[英]How to mock completablefuture.get()?

这是我试图模拟的方法:

@VisibleForTesting
public List<Row> processRows2(CompletableFuture future) {
    List<Row> rows2 = new ArrayList<>();
    try {
        DefaultAsyncResultSet beep = (DefaultAsyncResultSet) future.get();
        for (Row b : beep.currentPage()) {
            rows2.add(b);
        }
    }
    catch (ExecutionException | InterruptedException e) {
        LOGGER.error(e);
        LOGGER.error(e.getStackTrace());
        throw new RuntimeException(e.getMessage() + " - Check thread pool resources are enough, may be too many queries in queue");
    }
    return rows2;
}

问题是,当我尝试用它来测试它时(目前只是试图让它一直运行到成功或失败):

@Test
public void processRows2test() {
    FeatureDaoImpl gar = new FeatureDaoImpl(connection);
    CompletableFuture L = new CompletableFuture();
    gar.processRows2(L);
}

它无休止地挂着。 我的猜测是future.get() 挂在哪里; 我不确定。 但我不知道如何嘲笑它。 我试过这个:

@Mock
private CompletableFuture mockFutures;

@Before
    public void setUp() {
        try {
            Mockito.when(mockFutures.get()).thenReturn((AsyncResultSet) mockResultSetFuture);
        }
        catch (Exception e) {
        }
    }

但是这个我觉得是不对的。 try catch 是因为它在 get() 上对我大喊大叫未处理的异常,所以我不知道如何解决这个问题。

我现在也试过这个:

@Mock
final CompletableFuture<List<String>> mockedFuture = Mockito.mock(CompletableFuture.class);

在设置中使用以下内容:

    Mockito.doReturn(new ArrayList<Row>()).when(mockedFuture).get();

但它仍然无休止地挂起。

我见过这些:

如何在 Mockito 中模拟 CompletableFuture 的完成这个我不明白它到底想让我做什么,而且感觉不太适用,因为它不是一个 get 方法。 我在这里看到了一些包含 .get() 的示例......但不幸的是,没有一个是模拟方法,它们在测试本身中得到了: https ://www.javatips.net/api/java.util.concurrent.completablefuture

编辑:代码运行。 它返回结果。 所以并不是实际的方法没有返回一个值——我知道它会这样做,它现在正在 QA 中这样做。

您当前的CompletableFuture尚未完成,因此.get()方法挂起等待永远不会发生的异步完成。 您可以使用CompletableFuture.completedFuture(value)创建一个CompletableFuture实例,该实例将在调用.get()时返回传递的值。

您可以在此处使用CompletableFuture.completedFuture方法

@Test
public void processRows2test() {
    FeatureDaoImpl gar = new FeatureDaoImpl(connection);
    CompletableFuture L = CompletableFuture.completedFuture(new ArrayList<Row>());
    gar.processRows2(L);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM