Interview Questions

How To Group Test Cases Class using JUnit TestSuite?

JUnit Questions and Answers


(Continued from previous question...)

How To Group Test Cases Class using JUnit TestSuite?

Usually, there are many classes to be tested in a Java application. For each Java class in the application you need to write a JUnit test case class comtaining multiple test methods.

You could call a JUnit runner to run each JUnit test case class manually. But you should group all JUnit test case clases into a test suite with JUnit TestSuite. The following code and notes are provided by Varun Chopra and valid for JUnit 3.8 with some corrections.

To group all test case classes together and run them a single unit, you should create a new class named like AllTests.java. In this class you must create a "public static Test suite()" method, which returns a TestSuite object as a container of test case classes. See the sample code below:

public static Test suite ( ) {
 TestSuite suite= new TestSuite("All JUnit Tests");
 suite.addTest(DirListerTest.suite());
 return suite;
}

To add another test case class, say LogWriterTest, use suite.addTest(LogWriterTest.suite()); statement. Now your suite method will look like this:

public static Test suite ( ) {
 TestSuite suite= new TestSuite("All JUnit Tests");
 suite.addTest(DirListerTest.suite());
 suite.addTest(LogWriterTest.suite());
 return suite;
}

To run all test cases contained in this test suite, you should call a JUnit runner with the JVM command. But you can also add a main() method in AllTests.java:

public static void main (String[] args) {
 junit.textui.TestRunner.run(AllTests.class);
}

If you were using graphics view, then you need not to change your method to call suite. Therefore, following main() method will work to execute outer suite and containing suites

public static void main (String[] args) {
 junit.swingui.TestRunner.run(AllTests.class);
}

(Continued on next question...)

Other Interview Questions