Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 342
mt22 Avatar asked Jun 18 '12 09:06

mt22


People also ask

How do you test a method in JUnit?

A JUnit test is a method contained in a class which is only used for testing. This is called a Test class. To mark a method as a test method, annotate it with the @Test annotation. This method executes the code under test.

How do you test a thread?

To test multi-thread functionality, let the multiple instances of the application or program to be tested be active at the same time. Run the multi-thread program on different hardware. Thread testing is a form of session testing for which sessions are formed of threads.

How do you run a thread method?

Java Thread run() methodThe run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

How can an individual unit test method be executed or debugged?

Select the individual tests that you want to run, open the right-click menu for a selected test and then choose Run Selected Tests (or press Ctrl + R, T). If individual tests have no dependencies that prevent them from being run in any order, turn on parallel test execution in the settings menu of the toolbar.


2 Answers

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();
}
like image 167
Emmanuel Bourg Avatar answered Oct 17 '22 18:10

Emmanuel Bourg


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.

like image 39
John B Avatar answered Oct 17 '22 19:10

John B