0
0
JUnittesting~15 mins

Why test structure ensures clarity in JUnit - Automation Benefits in Action

Choose your learning style9 modes available
Verify structured JUnit test clarity with setup, test, and teardown
Preconditions (2)
Step 1: Create a test class named CalculatorTest
Step 2: Add a method annotated with @BeforeEach to initialize Calculator instance
Step 3: Add a test method annotated with @Test to verify add(2, 3) returns 5
Step 4: Add a method annotated with @AfterEach to clean up resources
Step 5: Run the test class
✅ Expected Result: Test runs successfully with clear structure: setup, test, teardown. Assertion passes confirming add method works.
Automation Requirements - JUnit 5
Assertions Needed:
Assert that add(2, 3) returns 5
Best Practices:
Use @BeforeEach for setup
Use @AfterEach for cleanup
Use descriptive method names
Keep test methods focused on one behavior
Use assertions to verify expected outcomes
Automated Solution
JUnit
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

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

public class CalculatorTest {
    private Calculator calculator;

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

    @Test
    void testAddTwoNumbers() {
        int result = calculator.add(2, 3);
        assertEquals(5, result, "Adding 2 and 3 should return 5");
    }

    @AfterEach
    void tearDown() {
        calculator = null; // Clean up
    }
}

This test class shows clear structure for clarity:

  • @BeforeEach setUp() creates a fresh Calculator before each test. This ensures tests do not share state.
  • @Test testAddTwoNumbers() tests one behavior: adding 2 and 3 returns 5. The assertion checks the expected result.
  • @AfterEach tearDown() cleans up by nullifying the calculator reference, showing good practice.

Using this structure makes tests easy to read and understand, like a recipe with clear steps: prepare, test, clean.

Common Mistakes - 3 Pitfalls
Not using @BeforeEach and initializing objects inside test methods
Writing multiple assertions testing different behaviors in one test method
Not cleaning up resources after tests
Bonus Challenge

Now add data-driven testing with 3 different pairs of numbers to test the add method

Show Hint