0
0
JUnittesting~15 mins

@Test annotation in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify addition method returns correct sum
Preconditions (2)
Step 1: Create a test class named CalculatorTest
Step 2: Write a test method named testAdd annotated with @Test
Step 3: Inside testAdd, call Calculator.add(2, 3)
Step 4: Assert that the result equals 5
✅ Expected Result: The test passes confirming that add(2, 3) returns 5
Automation Requirements - JUnit 5
Assertions Needed:
Assert that Calculator.add(2, 3) returns 5
Best Practices:
Use @Test annotation on test methods
Use meaningful method names
Use assertions from org.junit.jupiter.api.Assertions
Keep test methods independent and simple
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }
}

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

The @Test annotation marks the method testAdd as a test method for JUnit to run.

Inside testAdd, we call the add method from the Calculator class with inputs 2 and 3.

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

This simple structure shows how @Test helps JUnit identify and run test methods automatically.

Common Mistakes - 3 Pitfalls
Forgetting to annotate the test method with @Test
Using assert statements from java.lang instead of JUnit assertions
Naming test methods without descriptive names
Bonus Challenge

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

Show Hint