如何在Junit 4中自定义TestSuite测试?

时间:2013-10-06 17:00:08

标签: java junit

在下面的代码中,ExampleTest类包含5个测试。但是,我想使用JUNIT从ExampleTestSuite类中仅运行其中两个。

public class ExampleTest extends TestCase {
    private Example example;
    public ExampleTest(String name) {
        super(name);
    }

    protected void setUp() throws Exception {
        super.setUp();
        example= new Example();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        example= null;
    }

    public void test1() {

    }
    public void test2() {

    }
    public void test3() {

    }
    public void test4() {

    }
    public void test5() {

    }

}

这是我在JUnit 3中完成的代码,但是如何在JUnit版本4中完成?

public class ExampleTestSuite {

    public static Test suite() {
        TestSuite suite = new TestSuite(ExampleTestSuite.class.getName());
        suite.addTest(new ExampleTest("test1"));
        suite.addTest(new ExampleTest("test3"));
        return (Test) suite;
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用JUnit 4.8中介绍的Categories跑步者:

/**
 * Marker class to be used with the @Category annotation of JUnit.
 */
public class SmokeTests {}


/**
 * Your original test class converted to JUnit 4.
 */
public class ExampleTest {
    private Example example;

    @Before
    public void setUp() throws Exception {
        example = new Example();
    }

    @After
    public void tearDown() throws Exception {
        example = null;
    }

    @Test
    @Category(SmokeTests.class)
    public void test1() {}

    @Test
    public void test2() {}

    @Test
    @Category(SmokeTests.class)
    public void test3() {}

    @Test
    public void test4() {}

    @Test
    public void test5() {}
}


/**
 * Your original test suite class converted to JUnit 4.
 */
@RunWith(Categories.class)
@SuiteClasses(ExampleTest.class)
@IncludeCategory(SmokeTests.class)
public class ExampleTestSuite {}