Skip to content

Before and After

The annotations that designate methods to run before and after each test case have changed with JUnit 5.

@BeforeEach

This method will execute before each test case. * This was @Before in JUnit 4.

@BeforeEach
void setUp() {
}

@AfterEach

This method will execute after each test case. * This was @After in JUnit 4.

@AfterEach
void tearDown() {
}

Practice Exercise

There are annotations for executing methods when a class loads. * @BeforeAll * @AfterAll

These methods must be static, and execute once.


Drill

JUnit5/test/com.example.junit5.drills.AccountTests

  • Add a field private Account account to your test case.
  • Add a method to instantiate a new Account object before each test case.
  • Add a method to set the field to null after each test case.

(Solution: AccountTests2.java)


Prev -- Up -- Next