Test Overview
This test class demonstrates how to organize tests using JUnit 5. It includes setup and teardown methods and two simple test methods verifying basic math operations.
This test class demonstrates how to organize tests using JUnit 5. It includes setup and teardown methods and two simple test methods verifying basic math operations.
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { private Calculator calculator; @BeforeEach void setUp() { calculator = new Calculator(); } @AfterEach void tearDown() { calculator = null; } @Test void testAddition() { int result = calculator.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } @Test void testSubtraction() { int result = calculator.subtract(5, 3); assertEquals(2, result, "5 - 3 should equal 2"); } } class Calculator { int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit starts test run for CalculatorTest class | Test runner initialized, no tests executed yet | - | PASS |
| 2 | BeforeEach method setUp() is called to initialize Calculator instance | Calculator instance created and ready for test | - | PASS |
| 3 | testAddition() method is executed | Calculator instance available, inputs 2 and 3 provided | assertEquals verifies result is 5 | PASS |
| 4 | AfterEach method tearDown() is called to clean up Calculator instance | Calculator instance set to null | - | PASS |
| 5 | BeforeEach method setUp() is called again before next test | New Calculator instance created for next test | - | PASS |
| 6 | testSubtraction() method is executed | Calculator instance available, inputs 5 and 3 provided | assertEquals verifies result is 2 | PASS |
| 7 | AfterEach method tearDown() is called to clean up Calculator instance | Calculator instance set to null | - | PASS |
| 8 | JUnit completes test run for CalculatorTest class | All tests executed successfully | - | PASS |