10

As in the title, I want to test a method like this:

public void startThread()
{
    new Thread()
    {
        public void run()
        {
            myLongProcess();
        }
    }.start();
}

EDIT: Judging by comments I guess it is not very common to test if a thread starts or not. So I've to adjust the question... if my requirement is 100% code coverage do I need to test if that thread starts or not? If so do I really need an external framework?

2

2 Answers 2

7

This can be done elegantly with Mockito. Assuming the class is named ThreadLauncher you can ensure the startThread() method resulted in a call of myLongProcess() with:

public void testStart() throws Exception {
    // creates a decorator spying on the method calls of the real instance
    ThreadLauncher launcher = Mockito.spy(new ThreadLauncher());

    launcher.startThread();
    Thread.sleep(500);

    // verifies the myLongProcess() method was called
    Mockito.verify(launcher).myLongProcess();
}
5
  • 2
    I would consider mocking or spying the class under test a bad practice. Instead, verify what myLongProcess does. It must DO something, verify it. If it is calling for other class, Mock that class to verify the call.
    – John B
    Commented Jun 18, 2012 at 11:19
  • 1
    My understanding of the question is that he wants to test if the startThread() method does it's job of starting a thread. He doesn't ask how to test the result of myLongProcess(), I assume he already knowns how to do this. Commented Jun 18, 2012 at 11:26
  • If you aim at 100% coverage you will have to execute the startThread() method in your tests. You can do this as I suggested, or by checking the result of the execution of myLongProcess() if you don't want to import Mockito in your project. The difficulty will be to wait until the method completes to check the result. Commented Jun 18, 2012 at 13:29
  • Thread.sleep might cause other tests in the suite to be flaky and fail unexplicably
    – Amit Dash
    Commented Apr 23, 2018 at 10:53
  • @AmitDash How? Do you have an example? Commented Apr 23, 2018 at 16:20
1

If you need 100% coverage, you will need to call startThread which will kick off a thread. I recommend doing some sort of verification that the thread was stared (by verifying that something in myLongProcess is happening, then clean up the thread. Then you would probably do the remainder of the testing for myLongProcess by invoking that method directly from your unit test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.