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

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


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


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.