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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With