0
0
JUnittesting~15 mins

Test method naming conventions in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify test method naming conventions in JUnit
Preconditions (2)
Step 1: Create a test class named CalculatorTest
Step 2: Write a test method to verify addition functionality
Step 3: Name the test method using a clear, descriptive name following the convention: methodName_StateUnderTest_ExpectedBehavior
Step 4: Annotate the test method with @Test
Step 5: Run the test and verify it passes
✅ Expected Result: The test method runs successfully and the name clearly describes what is tested and expected
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the addition method returns the correct sum
Best Practices:
Use descriptive test method names following the pattern: methodName_StateUnderTest_ExpectedBehavior
Use @Test annotation from JUnit 5
Keep test methods small and focused
Use assertions from org.junit.jupiter.api.Assertions
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {

    @Test
    void add_TwoPositiveNumbers_ReturnsCorrectSum() {
        Calculator calculator = new Calculator();
        int result = calculator.add(3, 5);
        assertEquals(8, result, "3 + 5 should equal 8");
    }
}

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

The test class CalculatorTest contains a single test method named add_TwoPositiveNumbers_ReturnsCorrectSum. This name clearly states the method under test (add), the condition (TwoPositiveNumbers), and the expected result (ReturnsCorrectSum).

The method is annotated with @Test from JUnit 5 to mark it as a test method.

Inside the test, we create an instance of Calculator and call the add method with 3 and 5. We then assert that the result is 8 using assertEquals. The assertion message helps explain the expected behavior if the test fails.

This structure follows best practices by having a descriptive method name, using proper annotations, and clear assertions.

Common Mistakes - 3 Pitfalls
Using vague test method names like test1 or checkAddition
Not using the @Test annotation
Writing multiple assertions testing different behaviors in one test method
Bonus Challenge

Now add two more test methods for subtraction and multiplication following the same naming conventions.

Show Hint