JUnit5: Top 7 Good-To-Know things

Aleksei Novikov
3 min readMar 1, 2023

There is a list of the top 7 good-to-know things about JUnit5. But if you are not familiar with the framework, you’d better start with the official guide.

Test lifecycle

Every test is a method annotated with @Test. To add a readable name to a test method, use @DisplayMethod annotation.

To perform any actions before or after a test, use the following:

  • @Before, @BeforeAll — before every or before all tests
  • @After, @AfterAll — after every or after all tests

JUnit creates a new instance of a class per test. If you have, for example, 5 test methods, it will create 5 instances of the class to perform every test in isolation. If you want to have the only instance, use @TestInstance(Lifecycle.PER_CLASS) annotation. By the way, TestNG creates the only instance by default.

// Forces JUnit to reuse the same class instace per test
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TestService {

// Runs before every test
@Before
void setUp() {
}

// Runs before all tests
@BeforeAll
static void setUpAll() {
}

// Runs after every test
@After()
void tearDown() {
}

// Runs after all tests
@AfterAll
static void tearDownAll() {
}

// Display name is used by IDE and reports…

--

--