import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
class Calculator {
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
}
public class CalculatorTest {
private Calculator calculator;
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@AfterEach
void tearDown() {
calculator = null;
}
@Test
void testAdd() {
int result = calculator.add(5, 3);
assertEquals(8, result, "5 + 3 should equal 8");
}
@Test
void testSubtract() {
int result = calculator.subtract(10, 4);
assertEquals(6, result, "10 - 4 should equal 6");
}
}The @BeforeEach method setUp() runs before each test method. It creates a new Calculator instance so each test starts fresh, avoiding shared state.
The @AfterEach method tearDown() runs after each test method. It clears the Calculator reference to help with cleanup and avoid side effects.
Each test method uses the Calculator instance to perform operations and asserts the expected results. This shows how lifecycle hooks manage setup and teardown to keep tests independent and reliable.