Explore the test-driven development approach and learn how to write tests before implementing features.
@Test
- Mark methods as test cases@BeforeEach
- Setup common test fixtures@AfterEach
- Clean up resources after tests@BeforeAll
- One-time setup before all tests@AfterAll
- One-time teardown after all tests// 1. Write a Failing Test (Red) @Test void shouldAddTwoNumbers() { // Arrange Calculator calculator = new Calculator(); // Act int result = calculator.add(2, 3); // Assert assertEquals(5, result); } // 2. Write Minimal Implementation (Green) public class Calculator { public int add(int a, int b) { return a + b; } } // 3. Refactor (if needed) public class Calculator { /** * Adds two integers and returns the sum. * * @param a first operand * @param b second operand * @return the sum of the operands */ public int add(int a, int b) { return a + b; } } // Example of @BeforeEach usage class CalculatorTests { private Calculator calculator; @BeforeEach void setup() { calculator = new Calculator(); } @Test void shouldAddTwoNumbers() { assertEquals(5, calculator.add(2, 3)); } @Test void shouldHandleNegativeNumbers() { assertEquals(-1, calculator.add(2, -3)); } }