Verify addition method returns correct sum
Preconditions (1)
Step 1: Call add(2, 3)
Step 2: Capture the returned result
Step 3: Verify the result equals 5
✅ Expected Result: The add method returns 5 when called with 2 and 3
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class Calculator { public int add(int a, int b) { return a + b; } } public class CalculatorTest { @Test void testAddReturnsCorrectSum() { Calculator calculator = new Calculator(); int result = calculator.add(2, 3); assertEquals(5, result, "Addition result should be 5"); } }
This test uses JUnit 5 framework. The @Test annotation marks the method as a test. We create an instance of Calculator and call the add method with inputs 2 and 3. The returned result is stored in result. We then use assertEquals to check if result equals 5. If it does, the test passes, confirming the method works as expected. If not, the assertion fails and the test reports an error. This verifies the expected outcome clearly and simply.
Now add data-driven testing with 3 different input pairs and their expected sums