Skip to content

Common updates from JUnit 4 to JUnit 5

Alba Herrerías edited this page Sep 19, 2024 · 35 revisions

Tests

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

org.junit.jupiter.api.Test

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")

RunWith

Add imports:

import org.mockito.junit.jupiter.MockitoExtension;

import org.junit.jupiter.api.extension.ExtendWith;

Replace @RunWith(MockitoJUnitRunner.class) with @ExtendWith(MockitoExtension.class)

ClassRule

@ClassRule is deprecated in Junit5 and, unfortunately, the translation is not straight forward. It depends on the implementation. At the moment we have successfully migrated one of is usages in this PR

I'll explain this example:

  • Now the class has a new decorator @LoggerContextSource, to which we pass the value of the config file (value = "log4j2-jdbc-dbcp2.xml") and the timeout (the timeout value is from LoggerContextRule.createShutdownTimeoutLoggerContextRule)
  • In the test function, we no longer need to get the appender as it is provided as a parameter of the function.

Please update this section when they request changes for the PR we'll do in their side, to reflect the end result they are looking for.

Clone this wiki locally