Test Overview
This test checks if the Calculator class correctly adds two numbers using the Arrange-Act-Assert pattern. It verifies that the sum of 5 and 3 equals 8.
This test checks if the Calculator class correctly adds two numbers using the Arrange-Act-Assert pattern. It verifies that the sum of 5 and 3 equals 8.
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test public void testAdd() { // Arrange Calculator calculator = new Calculator(); int a = 5; int b = 3; // Act int result = calculator.add(a, b); // Assert assertEquals(8, result, "Sum should be 8"); } } class Calculator { public int add(int x, int y) { return x + y; } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes CalculatorTest class | — | PASS |
| 2 | Arrange: Create Calculator instance and set inputs a=5, b=3 | Calculator object created, variables a=5, b=3 assigned | — | PASS |
| 3 | Act: Call add method with a and b | Calculator.add(5, 3) called, returns 8 | — | PASS |
| 4 | Assert: Check if result equals 8 | Result is 8 | assertEquals(8, result) | PASS |
| 5 | Test ends successfully | Test passed with no errors | — | PASS |
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