Test Suite
/**
* TEST SUITE - RUN MULTIPLE TEST CLASSES TOGETHER
* -----------------------------------------------
* A Test Suite lets you group several test classes and run them as a unit.
*
* WHY USE A SUITE?
* ----------------
* - To run related tests together (e.g., integration tests)
* - To share expensive setup across multiple test classes
* - To control execution order
*
* In this example:
* - @BeforeClass opens a shared "database connection"
* - @AfterClass closes it
* - UserTest and OrderTest both run inside the same suite
*/
package com.minte9.junit.test_suite;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
UserTest.class,
OrderTest.class
})
public class SuiteTest {
@BeforeClass
public static void globalSetup() {
System.out.println("Connecting to test database...");
}
@AfterClass
public static void globalTeardown() {
System.out.println("Closing test databases...");
}
}
/*
Connecting to test database...
Running UserTest.testCreateUser
Running UserTest.testDeleteUser
Running OrderTest.testPlaceOrder
Closing test databases...
*/
T
package com.minte9.junit.test_suite;
import org.junit.Test;
public class UserTest {
@Test
public void testCreateUser() {
System.out.println("Running UserTest.testCreateUser");
// Imagine: insert user into mock DB
}
@Test
public void testDeleteUser() {
System.out.println("Running UserTest.testDeleteUser");
// Imagine: delete user from mock DB
}
}
T
package com.minte9.junit.test_suite;
import org.junit.Test;
public class OrderTest {
@Test
public void testPlaceOrder() {
System.out.println("Running OrderTest.testPlaceOrder");
// Imagine: insert order into mock DB
}
}
Questions and answers:
Clink on Option to Answer
1. What is a JUnit Test Suite used for?
- a) Running multiple test classes together as one unit
- b) Running only a single test method
2. Why might you use a test suite?
- a) To group related tests and optionally share setup
- b) To disable all tests in the project
3. When does a @BeforeClass method inside a suite run?
- a) Once before all test classes are executed
- b) Before every individual test method
4. What is the purpose of @AfterClass in a suite?
- a) Clean up shared resources after all tests finish
- b) Close resources after each individual test
5. What happens to the test classes listed in a suite definition?
- a) They run in the suite as part of one combined execution
- b) They are ignored unless executed manually
6. Why might a suite improve performance?
- a) It allows expensive setup (like database initialization) to run only once
- b) It automatically optimizes slow test code