Search⌘ K
AI Features

Solution: Bank Account Test Lifecycle

Explore how to manage the lifecycle of bank account tests using JUnit 5. Understand the use of @BeforeEach for test setup to maintain isolation and write precise tests for deposit and withdrawal functions, ensuring reliable verification of your business logic.

We'll cover the following...
Java 25
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import static org.junit.jupiter.api.Assertions.assertEquals;
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) {
this.balance += amount;
}
public void withdraw(double amount) {
this.balance -= amount;
}
public double getBalance() {
return balance;
}
}
public class MainTest {
private BankAccount account;
// Runs before EACH test method (testDeposit and testWithdraw)
@BeforeEach
void setUp() {
this.account = new BankAccount(100.0);
}
@Test
void testDeposit() {
account.deposit(50.0);
// Expect 100 + 50 = 150
assertEquals(150.0, account.getBalance(), "Balance should be 150.0 after deposit");
}
@Test
void testWithdraw() {
account.withdraw(30.0);
// Expect 100 - 30 = 70. Even if testDeposit ran first,
// @BeforeEach reset us back to 100.0 before this line.
assertEquals(70.0, account.getBalance(), "Balance should be 70.0 after withdrawal");
}
}
...