0
0
JUnittesting~15 mins

Why assertions verify expected outcomes in JUnit - Automation Benefits in Action

Choose your learning style9 modes available
Verify addition method returns correct sum
Preconditions (1)
Step 1: Call add(2, 3)
Step 2: Capture the returned result
Step 3: Verify the result equals 5
✅ Expected Result: The add method returns 5 when called with 2 and 3
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the returned value from add(2, 3) is equal to 5
Best Practices:
Use @Test annotation for test method
Use assertEquals for assertion
Keep test method name descriptive
Isolate test logic from production code
Automated Solution
JUnit
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 result should be 5");
    }
}

This test uses JUnit 5 framework. The @Test annotation marks the method as a test. We create an instance of Calculator and call the add method with inputs 2 and 3. The returned result is stored in result. We then use assertEquals to check if result equals 5. If it does, the test passes, confirming the method works as expected. If not, the assertion fails and the test reports an error. This verifies the expected outcome clearly and simply.

Common Mistakes - 3 Pitfalls
Not using assertions to verify results
Using incorrect assertion methods or parameters
Testing multiple things in one test method
Bonus Challenge

Now add data-driven testing with 3 different input pairs and their expected sums

Show Hint