0
0
JUnittesting~15 mins

Test independence in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that each test runs independently without relying on others
Preconditions (2)
Step 1: Create a test class CalculatorTest
Step 2: Write a test method testAddition that verifies add(2, 3) returns 5
Step 3: Write a test method testSubtraction that verifies subtract(5, 3) returns 2
Step 4: Run tests individually and together
Step 5: Verify that each test passes regardless of the order or if run alone
✅ Expected Result: Both testAddition and testSubtraction pass independently without any dependency on each other
Automation Requirements - JUnit 5
Assertions Needed:
assertEquals for verifying expected and actual results
Best Practices:
Each test method should be independent and not rely on shared state
Use @BeforeEach to set up fresh objects if needed
Avoid static or shared mutable state between tests
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

    int subtract(int a, int b) {
        return a - b;
    }
}

public class CalculatorTest {
    private Calculator calculator;

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

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

    @Test
    void testSubtraction() {
        int result = calculator.subtract(5, 3);
        assertEquals(2, result, "5 - 3 should equal 2");
    }
}

This test class CalculatorTest uses JUnit 5 to verify the Calculator methods.

The @BeforeEach method setUp() creates a new Calculator instance before each test. This ensures no shared state between tests.

Each test method (testAddition and testSubtraction) runs independently and asserts expected results using assertEquals.

Running tests individually or together will pass because they do not depend on each other.

Common Mistakes - 3 Pitfalls
Sharing the same Calculator instance across tests without resetting
Writing tests that depend on the order of execution
Using static variables to store test data or results
Bonus Challenge

Now add a test for multiplication with three different input pairs using parameterized tests

Show Hint