Skip to content

Common updates from JUnit 4 to JUnit 5

Ninette Adhikari edited this page Sep 19, 2024 · 35 revisions

Assertions

Update the import to org.junit.jupiter.api.Assertions

Note for any assertions with error messages, the message is moved as the second argument.

For example:

# JUnit 4
assertTrue("No messages returned", messages != null && messages.size() > 0);

#Junit 5
assertTrue(messages != null && messages.size() > 0, "No messages returned");

Before

Import: import org.junit.jupiter.api.BeforeEach

Replace @Before with @BeforeEach

BeforeClass

Import: import org.junit.jupiter.api.BeforeAll

Replace @BeforeClass with @BeforeAll

After

Import: import org.junit.jupiter.api.AfterEach

Replace @After with @AfterEach

AfterClass

Import: import org.junit.jupiter.api.AfterAll

Replace @AfterClass with @AfterAll

Category

Remove @Category because JUnit 5 doesn't support categories like JUnit 4. Instead, it uses tags (@Tag), which you can adapt based on your requirements.

Import @Tag like so: import org.junit.jupiter.api.Tag;

Then use @Tag as follows:

For example: @Category(AsyncLoggers.class) is replaced with @Tag("AsyncLoggers")

Tests

@Test remains the same. However instead of org.junit.Test you now use:

org.junit.jupiter.api.Test

Clone this wiki locally