0
0
JUnittesting~15 mins

Test class organization in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify proper organization of JUnit test class for Calculator
Preconditions (2)
Step 1: Create a test class named CalculatorTest in the test source folder
Step 2: Add a setup method annotated with @BeforeEach to initialize Calculator instance
Step 3: Add a test method annotated with @Test named testAdd
Step 4: In testAdd, call add(2, 3) and assert the result equals 5
Step 5: Run the test class
✅ Expected Result: Test class compiles and runs successfully, testAdd passes verifying add method returns correct sum
Automation Requirements - JUnit 5
Assertions Needed:
Assert that add(2, 3) returns 5
Best Practices:
Use @BeforeEach for setup
Name test class with suffix Test
Use descriptive test method names
Keep test methods independent
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

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

// 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 suffixing test classes with Test.

The @BeforeEach method setUp() creates a new Calculator instance before each test, ensuring tests do not share state.

The test method testAdd() is annotated with @Test and clearly describes what it tests.

Inside testAdd(), we call add(2, 3) and assert the result equals 5 using assertEquals. The assertion message helps understand failure if it occurs.

This organization keeps tests clean, readable, and independent, which is best practice in JUnit testing.

Common Mistakes - 4 Pitfalls
Not using @BeforeEach to initialize objects
{'mistake': "Naming test class without 'Test' suffix", 'why_bad': 'Makes it harder to identify test classes and some tools rely on naming conventions', 'correct_approach': "Name test classes with 'Test' suffix like CalculatorTest"}
Writing multiple assertions in one test method without clear purpose
Not providing assertion messages
Bonus Challenge

Now add two more test methods to testAdd with different inputs: (0, 0) and (-1, 1)

Show Hint