0
0
JUnittesting~15 mins

First JUnit test - Build an Automation Script

Choose your learning style9 modes available
Verify addition method returns correct sum
Preconditions (2)
Step 1: Create a class Calculator with a method add(int a, int b) that returns the sum of a and b
Step 2: Create a JUnit test class CalculatorTest
Step 3: Write a test method testAdd that calls add(2, 3)
Step 4: Assert that the result is 5
✅ Expected Result: The test passes confirming that add(2, 3) returns 5
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the returned sum equals the expected value
Best Practices:
Use @Test annotation for test methods
Use assertEquals for comparing expected and actual results
Keep test methods simple and focused
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 {
    int add(int a, int b) {
        return a + b;
    }
}

public class CalculatorTest {
    @Test
    void testAdd() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}

This code defines a simple Calculator class with an add method that sums two integers.

The CalculatorTest class contains a test method testAdd annotated with @Test, which JUnit 5 uses to identify test methods.

Inside testAdd, we create a Calculator instance, call add(2, 3), and store the result.

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

This structure follows best practices by keeping the test focused, using clear naming, and proper JUnit 5 annotations and assertions.

Common Mistakes - 4 Pitfalls
{'mistake': 'Forgetting to add the @Test annotation', 'why_bad': "JUnit will not recognize the method as a test, so it won't run", 'correct_approach': 'Always annotate test methods with @Test'}
Using assertEquals with parameters reversed (actual, expected)
Not importing static assertions
Writing multiple assertions in one test without clear purpose
Bonus Challenge

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

Show Hint