Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JUnit - Test Suite


May 15, 2021 jUnit



In a real project, as the project progresses, there will be more and more unit test classes, but until now we have only run the test classes one by one, which is certainly not feasible in the actual project practice. To solve this problem, JUnit provides a way to run test classes in bulk, called a test suite.

This way, each time you need to verify that the system is functionally correct, you can execute only one or more test suites. The test suite is very simple to write, and we need to follow the following rules:

  1. Create an empty class as the entry point to the test suite.
  2. Decorate this empty class with annotations org.junit.runner.runWith and org.junit.runners.SuiteClasses.
  3. Pass org.junit.runners.Suite as an argument to the annotation RunWith to prompt JUnit to perform for such a suite runner.
  4. An array of test classes that need to be placed into this test suite is used as parameters for annotation SuiteClasses.
  5. Ensure that this empty class uses public decoration and that there are exposed constructors without any parameters.

New JunitTestOne test class:

package test;

import org.junit.Assert;
import org.junit.Test;

/**类描述:
 *@author: zk
 *@date: 日期:2018-6-6 时间:下午3:56:17
 *@version 1.0
 */

public class JunitTestOne {

    @Test
    public void test() {
        System.out.println("测试一。。。");  
        Assert.assertTrue(true);  
    }

}

New JunitTestTwo test class:

package test;

import org.junit.Assert;
import org.junit.Test;

/**类描述:
 *@author: zk
 *@date: 日期:2018-6-6 时间:下午3:58:56
 *@version 1.0
 */

public class JunitTestTwo {

    @Test
    public void test() {
         System.out.println("测试二。。。");  
         Assert.assertTrue(true);  
    }

}

New test suite class:

JUnit - Test Suite

JUnit - Test Suite


package test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/**类描述:
 *@author: zk
 *@date: 日期:2018-6-6 时间:下午4:00:06
 *@version 1.0
 */

@RunWith(Suite.class)
@SuiteClasses({ JunitTestOne.class,JunitTestTwo.class })
public class AllTests {

}

JUnit - Test Suite

Test passed, console output:

JUnit - Test Suite

In the example code above, I put two test classes in the test suite AllTests, ran the test suite in Eclipse, and we could see that two test classes were called to execute. The test suite can contain not only basic test classes, but also other test suites, which makes it easy to layer unit test code for different modules.

Note: Be sure to ensure that there is no loop containing relationship between the test suites, otherwise endless loops will appear in front of us.