Master the most popular testing framework for Java, through the Learn JUnit course:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this tutorial, weβll learn how to migrate from JUnit 4 to the latest JUnit 5 release, with an overview of the differences between the two versions of the library.
For the general guidelines on using JUnit 5, see our article here.
2. JUnit 5 Advantages
Letβs start with the previous version, JUnit 4 , which has some clear limitations:
- A single jar library contains the entire framework. We need to import the whole library, even when we only require a particular feature. In JUnit 5, we get more granularity and can import only whatβs necessary.
- Only one test runner can execute tests at a time in JUnit 4 (e.g. SpringJUnit4ClassRunner or Parameterized ). JUnit 5 allows multiple runners to work simultaneously.
- JUnit 4 never advanced beyond Java 7, missing out on a lot of features from Java 8. JUnit 5 makes good use of the Java 8 features.
The idea behind JUnit 5 was to completely rewrite JUnit 4 in order to negate most of these drawbacks.
3. Differences
JUnit 4 was divided into the modules that comprise JUnit 5:
- JUnit Platform β this module scopes all the extension frameworks we might have an interest in: test execution, discovery, and reporting.
- JUnit Vintage β this module allows backward compatibility with JUnit 4 or even JUnit 3.
3.1. Annotations
JUnit 5 comes with important changes to its annotations. Instead of @org.junit.Test we now need to use @org.junit.jupiter.api.Test.
The most important one is that we can no longer use the @Test annotation for specifying expectations.
The expected parameter in JUnit 4:
@Test(expected = Exception.class)
public void shouldRaiseAnException() throws Exception {
// ...
}
Now we can use the method assertThrows:
void shouldRaiseAnException() throws Exception {
Assertions.assertThrows(Exception.class, () -> {
//...
});
}
The timeout attribute in JUnit 4:
@Test(timeout = 1)
public void shouldFailBecauseTimeout() throws InterruptedException {
Thread.sleep(10);
}
Now the assertTimeout method in JUnit 5:
@Test
void shouldFailBecauseTimeout() throws InterruptedException {
Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10));
}
Here are some other annotations that were changed within JUnit 5:
- @Before annotation is now @BeforeEach
- @After annotation is now @AfterEach
- @BeforeClass annotation is now @BeforeAll
- @AfterClass annotation is now @AfterAll
- @Ignore annotation is now @Disabled
3.2. Assertions
We can also write assertion messages in a lambda in JUnit 5, allowing the lazy evaluation to skip complex message construction until needed:
@Test
void shouldFailBecauseTheNumbersAreNotEqual_lazyEvaluation() {
Assertions.assertTrue(
2 == 3,
() -> "Numbers " + 2 + " and " + 3 + " are not equal!");
}
Furthermore, we can group assertions in JUnit 5:
@Test
void shouldAssertAllTheGroup() {
List<Integer> list = Arrays.asList(1, 2, 4);
Assertions.assertAll("List is not incremental",
() -> Assertions.assertEquals(list.get(0).intValue(), 1),
() -> Assertions.assertEquals(list.get(1).intValue(), 2),
() -> Assertions.assertEquals(list.get(2).intValue(), 3));
}
3.3. Assumptions
The new Assumptions class is now in org.junit.jupiter.api.Assumptions. JUnit 5 fully supports the existing assumptions methods in JUnit 4, and also adds a new set of methods allowing us to run some assertions under specific scenarios only:
@Test
void whenEnvironmentIsWeb_thenUrlsShouldStartWithHttp() {
assumingThat("WEB".equals(System.getenv("ENV")),
() -> assertTrue("http".startsWith(address)));
}
3.4. Tagging and Filtering
In JUnit 4, we could group tests by using the @Category annotation. In JUnit 5, the @Category annotation is replaced by the @Tag annotation:
@Tag("annotations")
@Tag("junit5")
class AnnotationTestExampleUnitTest {
/*...*/
}
We can include/exclude particular tags using the maven-surefire-plugin:
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<properties>
<includeTags>junit5</includeTags>
</properties>
</configuration>
</plugin>
</plugins>
</build>
3.5. New Annotations for Running Tests
In JUnit 4, we used the @RunWith annotation to integrate the test context with other frameworks or to change the overall execution flow in the test cases.
With JUnit 5, we can now use the @ExtendWith annotation to provide similar functionality.
As an example, to use the Spring features in JUnit 4:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
{"/app-config.xml", "/test-data-access-config.xml"})
public class SpringExtensionTest {
/*...*/
}
In JUnit 5, itβs a simple extension:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
{ "/app-config.xml", "/test-data-access-config.xml" })
class SpringExtensionTest {
/*...*/
}
3.6. New Test Rules Annotations
In JUnit 4, we used the @Rule and @ClassRule annotations to add special functionality to tests.
In JUnit 5. we can reproduce the same logic using the @ExtendWith annotation.
For example, say we have a custom rule in JUnit 4 to write log traces before and after a test:
public class TraceUnitTestRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
// Before and after an evaluation tracing here
...
}
};
}
}
And we implement it in a test suite:
@Rule
public TraceUnitTestRule traceRuleTests = new TraceUnitTestRule();
In JUnit 5, we can write the same in a much more intuitive manner:
public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback {
@Override
public void beforeEach(TestExtensionContext context) throws Exception {
// ...
}
@Override
public void afterEach(TestExtensionContext context) throws Exception {
// ...
}
}
Using JUnit 5βs AfterEachCallback and BeforeEachCallback interfaces, available in the org.junit.jupiter.api.extension package, we can easily implement this rule in the test suite:
@ExtendWith(TraceUnitExtension.class)
class RuleExampleUnitTest {
@Test
void whenTracingTests() {
/*...*/
}
}
3.7. JUnit 5 Vintage
JUnit Vintage aids in the migration of JUnit tests by running JUnit 3 or JUnit 4 tests within the JUnit 5 context.
We can use it by importing the JUnit Vintage Engine:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit5.vintage.version}</version>
<scope>test</scope>
</dependency>
4. Conclusion
JUnit 5 is a modular and modern take on the JUnit 4 framework. In this article, we introduced the major differences between these two versions and hinted at how to migrate from one to another.
