How to unit test a method that simply starts a thread with jUnit?

java, junit, multithreading, testing, unit-testing

Solution

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();
}

Problem

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?

Original source

Related problems