0
0
JUnittesting~15 mins

Unit testing concept in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify addition method returns correct sum
Preconditions (1)
Step 1: Create an instance of Calculator
Step 2: Call add(2, 3) method
Step 3: Capture the returned result
✅ Expected Result: The returned result should be 5
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the result of add(2, 3) is equal to 5
Best Practices:
Use @Test annotation for test methods
Use assertEquals for comparing expected and actual values
Keep tests independent and focused on one behavior
Name test methods clearly to describe what they test
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, "add(2, 3) should return 5");
    }
}

This test class CalculatorTest uses JUnit 5 to test the add method of the Calculator class.

The @Test annotation marks the method testAddReturnsCorrectSum as a test method.

Inside the test, we create a new Calculator object, call the add method with inputs 2 and 3, and store the result.

We then use assertEquals to check if the result is exactly 5. If it is, the test passes; otherwise, it fails.

This simple test ensures the addition logic works as expected.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not using @Test annotation on test methods', 'why_bad': "JUnit will not recognize the method as a test, so it won't run.", 'correct_approach': 'Always add @Test annotation above each test method.'}
Using assertEquals with parameters reversed (actual, expected)
Testing multiple behaviors in one test method
Not giving descriptive names to test methods
Bonus Challenge

Now add data-driven testing with 3 different input pairs for the add method

Show Hint