How to unit test a method that simply starts a thread with jUnit?
Solution 1
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();
}
Solution 2
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.
mt22
Updated on July 20, 2022Comments
-
mt22 almost 2 years
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?
-
John B almost 12 yearsI 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. -
Emmanuel Bourg almost 12 yearsMy 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 ofmyLongProcess()
, I assume he already knowns how to do this. -
Emmanuel Bourg almost 12 yearsIf 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 ofmyLongProcess()
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. -
Amit Dash about 6 years
Thread.sleep
might cause other tests in the suite to be flaky and fail unexplicably -
Emmanuel Bourg about 6 years@AmitDash How? Do you have an example?