0
0
JUnittesting~15 mins

Test classes and naming in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify correct naming and structure of JUnit test class
Preconditions (2)
Step 1: Create a test class named CalculatorTest in the test source folder
Step 2: Inside CalculatorTest, write a test method named testAdd that calls add(2, 3)
Step 3: Assert that the result of add(2, 3) is 5
Step 4: Run the test class using JUnit
✅ Expected Result: The test class CalculatorTest runs successfully and the testAdd method passes, confirming correct naming and structure
Automation Requirements - JUnit 5
Assertions Needed:
Assert that Calculator.add(2, 3) returns 5
Best Practices:
Test class name should be the class under test name plus 'Test' suffix
Test methods should be annotated with @Test
Use meaningful test method names
Keep test methods small and focused
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

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

// Simple Calculator class for reference
class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

This test class is named CalculatorTest following the convention of appending 'Test' to the class under test name.

The test method testAdd is annotated with @Test so JUnit knows to run it.

Inside the test method, we create an instance of Calculator and call the add method with inputs 2 and 3.

We use assertEquals to check that the result is 5, which is the expected sum.

This structure and naming make the test clear, focused, and easy to understand.

Common Mistakes - 4 Pitfalls
{'mistake': "Naming the test class without 'Test' suffix", 'why_bad': 'JUnit and many tools expect test classes to follow naming conventions to detect and run tests automatically.', 'correct_approach': "Name the test class as the class under test plus 'Test', e.g., CalculatorTest."}
{'mistake': 'Not annotating test methods with @Test', 'why_bad': "JUnit will not recognize methods as tests without the @Test annotation, so tests won't run.", 'correct_approach': 'Always add @Test annotation to each test method.'}
{'mistake': "Using vague test method names like 'test1' or 'check'", 'why_bad': 'Unclear names make it hard to understand what the test verifies.', 'correct_approach': 'Use descriptive names like testAdd or addTwoNumbersReturnsSum.'}
Writing multiple assertions testing different features in one test method
Bonus Challenge

Now add data-driven testing to verify add method with three different input pairs

Show Hint