adnan_252
adnan_252

Reputation: 421

How to assert after a Mockito mock object invokes a void method in another thread?

The constructor of the object under test starts a new thread that waits to take() from a queue, and when it finally does take it calls a void on the mock with the data. How do I make an assert that the queue is empty after the void is called on the mock?

CUT:

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:

@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?
}

Upvotes: 0

Views: 588

Answers (1)

airborn
airborn

Reputation: 2625

You should be able to use awaitility to test asynchronous code. This could be something like

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

Upvotes: 2

Related Questions