Verify addition method returns correct sum
Preconditions (1)
✅ Expected Result: The add method returns 5 when called with inputs 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 of 2 and 3 should be 5"); } }
This test class CalculatorTest uses JUnit 5 to check the add method of the Calculator class.
The @Test annotation marks the test method testAddReturnsCorrectSum. Inside, it creates a Calculator object, calls add(2, 3), and stores the result.
Then, assertEquals compares the expected value 5 with the actual result. If they match, the test passes; otherwise, it fails and shows the message.
This clear structure helps beginners understand how to write simple unit tests with assertions.
Now add data-driven testing with 3 different pairs of inputs and expected sums
assertEquals in JUnit testing?assertEquals with a message in JUnit?int expected = 5;
int actual = 3 + 2;
assertEquals(expected, actual);
assertEquals(5, "5");
assertEquals usage **including a custom error message** correctly checks if the returned list matches List.of("a", "b")?List<String> expected = List.of("a", "b");
List<String> actual = myMethod();Pass the test and this pattern moves unknown