Java JUnit Tutorial - JUnit TestSuite

A TestSuite contains a list of of Tests.

Following is the declaration for org.junit.TestSuite class:

public class TestSuite extends Object implements Test

TestSuite Class

A TestSuite is a Composite of Tests. It runs a collection of test cases.

The following list has some frequently used methods from TestSuite class.

  • void addTest(Test test)
    Adds a test to the suite.
  • void addTestSuite(Class<? extends TestCase> testClass)
    Adds the tests from the given class to the suite.
  • int countTestCases()
    Counts the number of test cases that will be run by this test.
  • String getName()
    Returns the name of the suite.
  • void run(TestResult result)
    Runs the tests and collects their result in a TestResult.
  • void setName(String name)
    Sets the name of the suite.
  • Test testAt(int index)
    Returns the test at the given index.
  • int testCount()
    Returns the number of tests in this suite.
  • static Test warning(String message)
    Returns a test which will fail and log a warning message.


The following code shows how to use the TestSuite Class

import junit.framework.*;
public class Main {
   public static void main(String[] a) {
      // add the test's in the suite
      TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.class );
      TestResult result = new TestResult();;
      System.out.println("Number of test cases = " + result.runCount());

Example 2

The following code shows how to use annotation to create Test Suite.

Create a java class and attach @RunWith(Suite.class) Annotation with class.

Add reference to Junit test classes using @Suite.SuiteClasses annotation

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
public class JunitTestSuite {   

Here is the code to run the Test Suite above.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(JunitTestSuite.class);
      for (Failure failure : result.getFailures()) {