JUnit 类别不适用于 TestCase?

JUnit Category doesn't work with TestCase?

我发现了一件奇怪的事情,我很想知道为什么会这样。我在 Junit 4.11 中使用 maven surefire 插件 ( 2.12.4 )。当我想使用 @Category 注释来禁用某些测试时。奇怪的是,它只能在不扩展 TestCase 的测试中正常工作。对于不扩展 TestCase 的测试,我只能将注释放在 run/disable 的测试方法上,但对于其他方法,它会禁用 class 中的所有测试。 例子: 命令行: mvn test -Dgroups=!testgroups.DisabledTests 运行 仅测试第一个代码段的 B:

import static org.junit.Assert.*;
public class DataTest {
    @Test
    public void testA(){...} 

    @Test @Category(testgroups.DisabledTests.class)
    public void testB(){...}
}

对于 class 扩展 TestCase 的第二种情况,它将 运行 没有测试。

public class DataTest extends TestCase {
    @Test
    public void testA(){...} 

    @Test @Category(testgroups.DisabledTests.class)
    public void testB(){...}
}

为什么会这样?

deborah-digges在评论中给出了解决方案:

The problem is that the second class is an extension of TestCase. Since this is JUnit 3 style, the annotation @Category didn't work. Annotating the class with @RunWith(JUnit4.class) should give you the same result in both cases

还有一个 Stefan Birkner:

JUnit 4 finds test by looking for the @Test annotation. You can remove the extends TestCase from your test class. Furthermore the name of the test method does no longer have to start with test. You're free to choose any method name you want.