Running JUnit Tests As A Test Suite In Junit 4.0 And Above – Code Sample

Running JUnit tests as test suite in JUnit 4.0 and above is extremely simple. If you are a newbie, test suite is a collection of Unit tests that can be run together. This is sometimes helpful if you want to run a group of JUnits rather than running the whole set of JUnits. In the following example, I have three imaginary test classes that I have called:

MyClassOneTest, MyClasTwoTest, MyClassThreeTest.

One way I can run those tests is to run them individually. If they are on the same package, eclipse allows you to right click on the package and do a Run as JUnit. But if they are distributed in several packages, and you don’t want to run everything on the package or the whole Test folder, you can group only those test cases that you want to run into a suite and run the suite which runs all the test classes as defined in the suite.As you can see in the class below, you need to define @RunWith(Suite.class) to denote that this is a test suite. Then you can group the classes under the annotation @Suite.suiteClasses({}) as comma separated classes.

 * @author Kushal Paudyal
 * This class show how you can run JUnit as a test suite
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import com.sanjaal.junit.MyClassOneTest;
import com.sanjaal.junit.MyClassTwoTest;
import com.sanjaal.junit.MyClassThreeTest;


public class MyClassesTestsSuite { }

You might immediately ask a question what happens if I create a test suite and run the whole packae as a Junit test? Will the JUnit Classes under the test suite be run two times (one as a class under the package, another as a test suite)? I saw that JUnit is smart enough to not run the test classes under JUnit if it exists under the package that you running as a whole. So you will not end up running the same test classes two times.

[My Video Promotion]
Tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.