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?

mt22
  • 323
  • 1
  • 6
  • 14

2 Answers2

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();
}
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
  • 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 Jun 18 '12 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. – Emmanuel Bourg Jun 18 '12 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. – Emmanuel Bourg Jun 18 '12 at 13:29
  • `Thread.sleep` might cause other tests in the suite to be flaky and fail unexplicably – Amit Dash Apr 23 '18 at 10:53
  • @AmitDash How? Do you have an example? – Emmanuel Bourg Apr 23 '18 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.

John B
  • 32,493
  • 6
  • 77
  • 98