0
0
JUnittesting~15 mins

CI pipeline test stage in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify CI pipeline test stage runs unit tests and reports results
Preconditions (2)
Step 1: Trigger the CI pipeline manually or by pushing code
Step 2: Wait for the test stage to start and complete
Step 3: Check the test stage logs for test execution details
Step 4: Verify that all unit tests are executed
Step 5: Verify that the test results are reported in the CI system
✅ Expected Result: The test stage completes successfully with all unit tests run and results reported without errors
Automation Requirements - JUnit 5
Assertions Needed:
Assert that all expected test methods are executed
Assert that no tests failed
Assert that test results are generated and accessible
Best Practices:
Use @Test annotations for test methods
Use assertions from org.junit.jupiter.api.Assertions
Keep tests independent and repeatable
Use descriptive test method names
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class SampleUnitTest {

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

    @Test
    void testStringContains() {
        String text = "Hello CI Pipeline";
        assertTrue(text.contains("CI"), "Text should contain 'CI'");
    }

    @Test
    void testArrayNotEmpty() {
        int[] numbers = {1, 2, 3};
        assertNotEquals(0, numbers.length, "Array should not be empty");
    }

}

This JUnit 5 test class SampleUnitTest contains three simple unit tests.

Each test method is annotated with @Test so the CI pipeline test stage will detect and run them automatically.

Assertions check expected outcomes: assertEquals verifies addition, assertTrue checks string content, and assertNotEquals ensures the array is not empty.

When the CI pipeline runs mvn test, it will execute these tests and report results. If all assertions pass, the test stage will succeed.

This setup ensures the CI pipeline test stage runs unit tests and reports results as expected.

Common Mistakes - 4 Pitfalls
Not using @Test annotation on test methods
Using System.out.println instead of assertions
Writing dependent tests that rely on execution order
Ignoring test failures in CI pipeline logs
Bonus Challenge

Now add data-driven testing with 3 different inputs for a method that checks if a number is even

Show Hint