Home » Java » Core Java » A JUnit Rule to Run a Test in Its Own Thread

About Frank Appel

A JUnit Rule to Run a Test in Its Own Thread

Occasionally it would be helpful to be able to run a JUnit test in a separate thread. In particular when writing integration tests that interact with encapsulated ThreadLocals or the like this could come in handy. A separate thread would implicitly ensure that the thread related reference of the threadlocal is uninitialized for each test run. This post introduces a JUnit Rule that provides such a functionality and explains how to use it.

To begin with take a look at the following example. It depicts a test case that produces intermittent failures of testB. The reason for this is that the outcome depends on the execution order of all tests due to side effects1. More precisely Display.getDefault() in principle returns a lazily instantiated singleton, while Display.getCurrent() is a simple accessor of this singleton. As a consequence testB fails if it runs after testA2.

public class FooTest {

  @Test
  public void testA() {
    Display actual = Display.getDefault();

    assertThat( actual ).isNotNull();
  }

  @Test
  public void testB() {
    Display actual = Display.getCurrent();

    assertThat( actual ).isNull();
  }
}

To avoid some behind-the-scene-magic, which bears the risk to make code less understandable, we could ensure that an existing display is disposed before the actual test execution takes place3.

@Before
  public void setUp() {
    if( Display.getCurrent() != null ) {
      Display.getCurrent().dispose();
    }
  }

Unfortunately this approach cannot be used within an integration test suite that runs PDE tests for example. The PDE runtime creates a single Display instance, whose lifetime spans all test runs. So display disposal would not be an option and testB would fail within PDE test suite execution all the time4.

At this point it is important to remember that the Display singleton is bound to its creation thread (quasi ThreadLocal)5. Because of this testB should run reliable, if executed in its own thread.

However thread handling is usually somewhat cumbersome at best and creates a lot of clutter, reducing the readability of test methods. This gave me the idea to create a TestRule implementation that encapsulates the thread handling and keeps the test code clean:

public class FooTest {

  @Rule
  public RunInThreadRule runInThread = new RunInThreadRule();

  @Test
  public void testA() {
    Display actual = Display.getDefault();

    assertThat( actual ).isNotNull();
  }

  @Test
  @RunInThread
  public void testB() {
    Display actual = Display.getCurrent();

    assertThat( actual ).isNull();
  }
}

The RunInThreadRule class allows to run a single test method in its own thread. It takes care of the demon thread creation, test execution, awaiting of thread termination and forwarding of the test outcome to the main thread. To mark a test to be run in a separate thread the test method has to be annotated with @RunInThread as shown above.

With this in place testB is now independent from the execution order of the tests and succeeds reliable. But one should be careful not to overuse RunInThreadRule. Although the @RunInThread annotation signals that a test runs in a separate thread it does not explain why. This may easily obfuscate the real scope of such a test. Hence I use this usually only as a last resort solution. E.g. it may be reasonable in case when a third party library relies on an encapsulated ThreadLocal that cannot be cleared or reset by API functionality.

For those who like to check out the RunInThreadRule implementation I have created a GitHub gist:

https://gist.github.com/fappel/65982e5ea7a6b2fde5a3

For a real-world usage you might also have a look at the PgmResourceBundlePDETest implementation of our Gonsole project hosted at:

https://github.com/rherrmann/gonsole.
 

  1. Note that JUnit sorts the test methods in a deterministic, but not predictable, order by default
  2. Consider also the possibility that testA might be in a other test case and the problem only occurs when running a large suite
  3. Then again I don’t like this kind of practice either, so for a more sophisitcated solution you may have a look at the post A JUnit Rule to Ease SWT Test Setup
  4. In the meanwhile you have probably recognized that the simplistic example test case is not very useful, but I hope it is sufficient to get the motivation explained.
  5. This makes such a thread the user interface thread in SWT. SWT implements a single-threaded UI model often called apartment threading
Reference: A JUnit Rule to Run a Test in Its Own Thread from our JCG partner Frank Appel at the Code Affine blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*


9 − = eight

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close