Verify addition of two numbers using Arrange-Act-Assert pattern
Preconditions (2)
✅ Expected Result: The test passes confirming that 5 + 3 equals 8
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 testAdd_TwoNumbers_ReturnsSum() { // Arrange Calculator calculator = new Calculator(); // Act int result = calculator.add(5, 3); // Assert assertEquals(8, result, "5 + 3 should equal 8"); } }
This test uses the Arrange-Act-Assert pattern:
This clear separation helps understand what is setup, what is tested, and what is verified.
Now add data-driven testing with 3 different pairs of numbers to verify addition
void testSum() {
int a = 5;
int b = 3;
int result = Calculator.add(a, b);
assertEquals(8, result);
}Which part of the Arrange-Act-Assert pattern does int result = Calculator.add(a, b); represent?@Test
void testMultiply() {
int x = 4;
int y = 2;
int product = x * y;
assertEquals(8, x * y);
}int product = x * y; which is correct.x * y directly instead of using the product variable, which breaks the pattern clarity.divide(int a, int b) that throws IllegalArgumentException when b is zero. Using Arrange-Act-Assert, which is the best way to write this test in JUnit 5?a to any number and b to zero to trigger the exception.assertThrows(IllegalArgumentException.class, () -> divide(a, b)) to check the exception is thrown.Pass the test and this pattern moves unknown