Part 10 / Topic 6 of 12
@BeforeEach and friends: a clean start for every test
BankAccountTest needs a fresh BankAccount before every single test — if one test deposits ₹500 and the next test assumes a clean ₹1000 balance, the second test's result depends on the order tests happened to run in, which is exactly the kind of bug a test suite exists to prevent, not cause.
class BankAccountTest {
private FakeAlertService alertService;
private BankAccount account;
@BeforeAll
static void announceSuite() {
System.out.println("Starting BankAccountTest suite");
}
@AfterAll
static void announceDone() {
System.out.println("Finished BankAccountTest suite");
}
@BeforeEach
void createFreshAccount() {
alertService = new FakeAlertService();
account = new BankAccount("Asha", 1000.0, alertService);
}
@Test
void withdraw_lessThanBalance_decreasesBalance() {
account.withdraw(300.0);
assertEquals(700.0, account.getBalance());
}
// ...
}
| Annotation | Runs | Typical use |
|---|---|---|
@BeforeEach |
before every @Test method |
build fresh test data — exactly what createFreshAccount does above |
@AfterEach |
after every @Test method |
clean up a resource a test opened (a file, a connection) |
@BeforeAll |
once, before any test in the class | expensive one-time setup; method must be static |
@AfterAll |
once, after every test in the class | expensive one-time teardown; method must be static |
@BeforeAll/@AfterAll must be static because they run before any instance of the test class exists — there is no this yet for an instance method to belong to. The real run in Section 12 shows Starting BankAccountTest suite printed exactly once above the tree, and Finished BankAccountTest suite printed exactly once after it — proof the "once per class" promise is real, not just documentation.
Full programs: examples/bank-and-discount/BankAccount.java, examples/bank-and-discount/BankAccountTest.java.
Done here? The practice set for Part 10 — including the solutions — is on the part page.