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

标签 java junit

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

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;
    }
}

最佳答案

您可以使用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 {}

关于java - 如何在 Junit 4 中自定义 TestSuite 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19211442/

相关文章:

java - Mockito - 验证方法是否重启次数?

java - 如何在不遇到 NoSuchTableException 的情况下使用带有普通 JDBC 和 HSQLDB 的 DBUnit 进行测试?

java - 为路由中的可选查询参数分配空默认值 - Play Framework

java - 为什么这个 OpenGL ES 代码不能创建纹理?

java - Java 中 Class 类型的可变参数

java - 在 JUnit 中使用 inputStream 时出现 MalformedURLException

java - 验证完成后,EasyMock 在 tearDown 方法中验证对 mock 的调用

java - 从 BigDecimal 中删除小数结尾的零

java - 在 GWT 应用程序中显示 PDF 文件

Java MongoDB 在多个字段中搜索值