0
0
JUnittesting~15 mins

Test suites with @Suite in JUnit - Build an Automation Script

Choose your learning style9 modes available
Create and run a JUnit test suite using @Suite
Preconditions (2)
Step 1: Create a new Java class named AllTestsSuite
Step 2: Annotate the class with @Suite and @SelectClasses
Step 3: Include the two existing test classes in @SelectClasses
Step 4: Run the AllTestsSuite class as a JUnit test
Step 5: Observe that all tests from the included classes run
✅ Expected Result: All test methods from the specified test classes run successfully when running the suite class
Automation Requirements - JUnit 5
Assertions Needed:
Verify that all tests from included classes are executed
Verify that the suite class runs without errors
Best Practices:
Use @Suite and @SelectClasses annotations properly
Keep test classes independent and focused
Name the suite class clearly to indicate it is a test suite
Automated Solution
JUnit
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectClasses({CalculatorTest.class, StringUtilsTest.class})
public class AllTestsSuite {
    // This class remains empty, it is used only as a holder for the above annotations
}

// Example test class 1
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {
    @Test
    void addition() {
        assertEquals(5, 2 + 3);
    }
}

// Example test class 2
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;

public class StringUtilsTest {
    @Test
    void isEmptyReturnsTrueForEmptyString() {
        assertTrue("".isEmpty());
    }
}

The AllTestsSuite class is annotated with @Suite and @SelectClasses to specify which test classes to run together.

The suite class itself has no methods; it just groups the tests.

Two example test classes, CalculatorTest and StringUtilsTest, each have simple test methods with assertions.

Running AllTestsSuite will run all tests from both classes, verifying the suite setup works.

Common Mistakes - 3 Pitfalls
Not annotating the suite class with @Suite
{'mistake': 'Using @RunWith(Suite.class) from JUnit 4 in JUnit 5 projects', 'why_bad': 'JUnit 5 uses different annotations and runners; mixing versions causes tests not to run.', 'correct_approach': "Use JUnit 5's @Suite and @SelectClasses annotations for test suites."}
Including test classes that do not have any test methods
Bonus Challenge

Add a third test class to the suite and verify all three classes run together

Show Hint