Verify addition method returns correct sum
Preconditions (1)
✅ Expected Result: The returned result should be 5
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, "add(2, 3) should return 5"); } }
This test class CalculatorTest uses JUnit 5 to test the add method of the Calculator class.
The @Test annotation marks the method testAddReturnsCorrectSum as a test method.
Inside the test, we create a new Calculator object, call the add method with inputs 2 and 3, and store the result.
We then use assertEquals to check if the result is exactly 5. If it is, the test passes; otherwise, it fails.
This simple test ensures the addition logic works as expected.
Now add data-driven testing with 3 different input pairs for the add method
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class CalcTest {
@Test
void testSum() {
int result = 2 + 3;
assertEquals(5, result);
}
}import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SampleTest {
@Test
public void testMultiply() {
int result = 3 * 4
assertEquals(12, result);
}
}Pass the test and this pattern moves unknown