TestSuite创建方式(一)

本文介绍了一个使用 JUnit 框架创建测试套件的示例代码。该示例展示了如何通过 TestSuite 类组织多个测试类,并利用 TestSetup 进行一次性的 setUp 和 tearDown 操作。
public class MyTestSuite extends TestCase {

    public MyTestSuite () {
        super();
    }

    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.addTest(new JUnit4TestAdapter(A.class));
        suite.addTest(new JUnit4TestAdapter(B.class));
        TestSetup wrapper = new TestSetup(suite) {
            @Before
            protected void setUp() throws LTFSLEBaseException, Exception { 
                oneTimeSetUp();
            }
           @After
            protected void tearDown() throws LTFSLEBaseException, Exception {
                oneTimeTearDown();
            }
        };
        return wrapper;
    }

    protected static void oneTimeSetUp() {
    }

    protected static void oneTimeTearDown(){

    }


### JUnit TestSuite的介绍 JUnit TestSuite 是 JUnit 框架中的个重要概念,它允许将多个测试用例组合在起,作为个整体进行执行。通过使用 TestSuite,可以将相关的测试用例组织起来,方便对组功能或模块进行统测试。 ### JUnit TestSuite的使用方法 1. **创建测试类**:编写多个继承自 `TestCase` 的测试类,每个测试类中包含多个以 `test` 开头的测试方法,这些方法会被自动识别为测试用例。 2. **创建 TestSuite**:在个类中创建个静态方法,返回个 `TestSuite` 对象。在这个方法中,使用 `TestSuite` 的构造函数将需要组合的测试类添加到测试套件中。 3. **运行 TestSuite**:在 `main` 方法中,使用 `junit.textui.TestRunner.run(suite())` 方法来运行创建好的测试套件。 ### JUnit TestSuite的示例 以下是个简单的 JUnit TestSuite 示例代码: ```java import junit.framework.*; import java.util.*; public class SimpleTest extends TestCase { public SimpleTest(String name) { super(name); } /** * 写个测试方法断言期望的结果 * JUnit推荐的做法是以test作为待测试的方法的开头,这样这些方法可以被自动找到并被测试。 */ public void testEmptyCollection() { System.out.println("in testEmptyCollection"); Collection collection = new ArrayList(); assertTrue(collection.isEmpty()); } public void test1() { System.out.println("in test1"); } public void test2() { System.out.println("in test2"); } public void test3() { System.out.println("in test3"); } public static Test suite() { // Constructs a TestSuite from the given class. // Adds all the methods of the class starting with "test" as test cases to the suite. return new TestSuite(SimpleTest.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } } ``` 在这个示例中,`SimpleTest` 类继承自 `TestCase`,包含了多个以 `test` 开头的测试方法。`suite` 方法返回个 `TestSuite` 对象,将 `SimpleTest` 类中的所有测试方法添加到测试套件中。最后,在 `main` 方法中运行这个测试套件。[^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值