How to unit test a method that just starts a thread using jUnit?

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

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

EDIT: Judging by the comments, I think it's not very common to check if a thread starts or not. So I have to tweak the question ... if my requirement is 100% code coverage, do I need to check if this thread starts or not? Should I really need an external structure?

+5
source share
2 answers

This can be done elegantly with Mockito . Assuming the class has a name ThreadLauncher, you can verify that the method startThread()led to a call 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();
}
+6
source

100% - , startThread, . , (, - myLongProcess, . , , myLongProcess, unit test.

+1

All Articles