How to Unit Test a Thread which has an infinite loop? [closed]

Posted on


I wanted to be sure the thread being tested would complete its job by the Assert statement of the unit test, but I couldn’t be sure bc of the way I designed the threads. I designed them to run forever in the background, performing a task – logging, assembling, or disassembling – at regular timed intervals. What I ended up doing was sleeping the test thread for a bit to ensure the thread being tested had enough time to complete its task. I have no idea whether this is the “right” way to handle this situation, and I’d appreciate any feedback!

// Tests whether thread removes completed tasks from in_progress and returns
// processors to available
public void testOne() {

    t.complete = true;

    try {
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block

    Assert.assertEquals(cs.size(), 3);
    Assert.assertEquals(inProgressJobs.size(), 0);


Full code:


When you want to test things that happened asynchronously, one solution is to give them some time to happen as you did. A bit more practical approach is to check if the assert condition is met in a loop and sleep a bit between the checks. if the condition is met no need to continue waiting. eventually, it needs to stop after a few tries or you have an infinite loop in your test.

Usually, you need to use this approach in E2E / Integration tests and not unit tests.

Leave a Reply

Your email address will not be published. Required fields are marked *