0
0
JUnittesting~15 mins

assertEquals in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify addition method returns correct sum
Preconditions (1)
Step 1: Call add(2, 3) method
Step 2: Capture the returned result
Step 3: Compare the result with expected value 5
✅ Expected Result: The add method returns 5 when called with inputs 2 and 3
Automation Requirements - JUnit 5
Assertions Needed:
Verify that the actual sum equals the expected sum using assertEquals
Best Practices:
Use @Test annotation for test methods
Use descriptive method names
Keep tests independent and simple
Use assertEquals(expected, actual) with a message for clarity
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 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.

Common Mistakes - 3 Pitfalls
Swapping expected and actual parameters in assertEquals
{'mistake': 'Not using @Test annotation on test methods', 'why_bad': "Without @Test, the test method won't run automatically, so tests are skipped silently.", 'correct_approach': 'Always annotate test methods with @Test to ensure they run.'}
Not providing a failure message in assertEquals
Bonus Challenge

Now add data-driven testing with 3 different pairs of inputs and expected sums

Show Hint