1. Introduction

In this quick article, we'll cover the usage of the @RunWith annotation in the JUnit 5 framework.

In JUnit 5, the @RunWith annotation has been replaced by the more powerful @ExtendWith annotation.

However, the @RunWith annotation can still be used in JUnit5 for the sake of the backward compatibility.

2. Running Tests With a JUnit4-Based Runner

We can run JUnit5 tests with any other older JUnit environment using the @RunWith annotation.

Let's see an example of running these tests in an Eclipse version that only supports JUnit4.

First, let's create the class we're going to test:

public class Greetings { public static String sayHello() { return "Hello"; } }

Next, let's create this plain JUnit5 test:

public class GreetingsTest { @Test void whenCallingSayHello_thenReturnHello() { assertTrue("Hello".equals(Greetings.sayHello())); } }

Finally, let's add this annotation to be able to run the test:

@RunWith(JUnitPlatform.class) public class GreetingsTest { // ... }

The JUnitPlatform class is a JUnit4-based runner that let us run JUnit4 tests on the JUnit Platform.

Let's keep in mind that JUnit4 does not support all the features of the new JUnit Platform, so this runner has a limited functionality.

If we check the result of the test in Eclipse we can see that a JUnit4 runner was used:

3. Running Tests in a JUnit5 Environment

Let's now run the same test in an Eclipse version that supports JUnit5. In this case, we don't need the @RunWith annotation anymore and we can write the test without a runner:

public class GreetingsTest { @Test void whenCallingSayHello_thenReturnHello() { assertTrue("Hello".equals(Greetings.sayHello())); } }

The test result shows that we're now using the JUnit5 runner:

4. Migrating from a JUnit4-Based Runner

Let's now migrate a test that uses a JUnit4-based runner to JUnit5.

We're going to use a Spring test as an example:

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringTestConfiguration.class }) public class GreetingsSpringTest { // ... }

If we want to migrate this test to JUnit5 we need to replace the @RunWith annotation with the new @ExtendWith:

@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { SpringTestConfiguration.class }) public class GreetingsSpringTest { // ... }

The SpringExtension class is provided by Spring 5 and integrates the Spring TestContext Framework into JUnit 5. The @ExtendWith annotation accepts any class that implements the Extension interface.

5. Conclusion

In this brief article, we covered the use of the JUnit 4's @RunWith annotation in the JUnit5 framework.

The full source code for the examples is available over on GitHub.