Verify JUnit test execution and assertion
Preconditions (2)
✅ Expected Result: The test passes successfully, confirming that JUnit runs the test and validates the assertion
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class Calculator { public int add(int a, int b) { return a + b; } } public class CalculatorTest { @Test void testAdd() { Calculator calc = new Calculator(); int result = calc.add(2, 3); assertEquals(5, result, "2 + 3 should equal 5"); } }
This code defines a simple Calculator class with an add method. The CalculatorTest class uses JUnit 5's @Test annotation to mark the test method. Inside testAdd, it creates a Calculator instance, calls add(2, 3), and asserts the result equals 5 using assertEquals. This shows how JUnit runs tests and checks results, making it the standard for Java testing because it is simple, clear, and integrates well with Java projects.
Now add data-driven testing with 3 different pairs of inputs and expected sums
JUnit considered the standard testing framework for Java?@Test
void testSum() {
int result = 2 + 3;
assertEquals(5, result);
}@Test
public void testDivide() {
int result = 10 / 0;
assertEquals(0, result);
}Pass the test and this pattern moves unknown