gpt4 book ai didi

java - 如何在 Mockito 模拟对象调用另一个线程中的 void 方法后断言?

转载 作者:行者123 更新时间:2023-12-02 05:33:05 25 4
gpt4 key购买 nike

被测试对象的构造函数启动一个新线程,等待从队列中获取take(),当它最终获取时,它会在模拟上调用带有数据的void。在模拟上调用 void 后,如何断言队列为空?

剪切:

public class MsgHandler {
LinkedBlockingQueue<String> outQueue = ...

public MsgHandler(Connection conn, ...) {
new Thread(() -> {
while (true) try {
conn.async(outQueue.take()); //void method call here
} catch (...) {...}
}).start();
...
}
}

测试:

@Test 
public void testOutboundMessageSentImmediately() throws Exception{
Connection conn = mock(Connection.class); //create mock Connection
MsgHandler handler = new MsgHandler(conn,...); //create CUT
doNothing().when(conn).async("query");
outQueue.add("query")
assertTrue(outQueue.isEmpty()); //how do I do this after the when?
}

最佳答案

您应该能够使用awaitility测试异步代码。这可能是这样的

await().atMost(5, SECONDS).untilCall(outQueue::isEmpty, is(true));

关于java - 如何在 Mockito 模拟对象调用另一个线程中的 void 方法后断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25335874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com