Verify structured JUnit test clarity with setup, test, and teardown
Preconditions (2)
✅ Expected Result: Test runs successfully with clear structure: setup, test, teardown. Assertion passes confirming add method works.
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class Calculator { int add(int a, int b) { return a + b; } } public class CalculatorTest { private Calculator calculator; @BeforeEach void setUp() { calculator = new Calculator(); } @Test void testAddTwoNumbers() { int result = calculator.add(2, 3); assertEquals(5, result, "Adding 2 and 3 should return 5"); } @AfterEach void tearDown() { calculator = null; // Clean up } }
This test class shows clear structure for clarity:
Using this structure makes tests easy to read and understand, like a recipe with clear steps: prepare, test, clean.
Now add data-driven testing with 3 different pairs of numbers to test the add method
@Test
void testSum() {
int a = 2;
int b = 3;
int result = a + b;
assertEquals(5, result);
} @Test
void testMultiply() {
int a = 4;
int b = 5;
int result = a * b
assertEquals(20, result);
}Pass the test and this pattern moves unknown