0
0
JUnittesting~15 mins

IDE integration (IntelliJ, Eclipse) in JUnit - Build an Automation Script

Choose your learning style9 modes available
Run a JUnit test in IntelliJ and Eclipse IDEs
Preconditions (3)
Step 1: Open the IDE and load the Java project with JUnit tests
Step 2: Locate the test class named CalculatorTest.java
Step 3: Right-click on CalculatorTest.java file
Step 4: Select 'Run CalculatorTest' option from the context menu
Step 5: Wait for the test execution to complete
Step 6: Observe the test results in the IDE's test runner window
✅ Expected Result: The test runner window shows that all tests in CalculatorTest.java passed successfully with green indicators
Automation Requirements - JUnit 5
Assertions Needed:
Verify that the test method 'testAddition' passes
Verify that the test runner output contains 'Tests passed: 1'
Best Practices:
Use @Test annotation for test methods
Use assertions from org.junit.jupiter.api.Assertions
Keep test methods independent and small
Use IDE's built-in test runner to execute tests
Do not hardcode file paths or environment-specific settings
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {

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

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

This code defines a simple JUnit 5 test class CalculatorTest with one test method testAddition. The test creates an instance of Calculator and calls its add method with inputs 2 and 3. It then asserts that the result equals 5 using assertEquals. The @Test annotation marks the method as a test for the IDE to detect. The Calculator class is included here for completeness.

When you right-click this test class in IntelliJ or Eclipse and select 'Run', the IDE uses its built-in JUnit runner to execute the test. The test runner window will show a green bar indicating the test passed. This confirms the IDE integration is working correctly.

Common Mistakes - 4 Pitfalls
Not adding JUnit 5 dependency to the project
Using @Test annotation from JUnit 4 instead of JUnit 5
Running tests without building the project first
Hardcoding file paths or environment variables in tests
Bonus Challenge

Now add data-driven testing with 3 different input pairs for the add method

Show Hint