【问题标题】:Is it possible to name a test suite in JUnit 4?是否可以在 JUnit 4 中命名测试套件?
【发布时间】:2016-01-12 13:32:03
【问题描述】:

在 JUnit3 中,可以这样命名一个测试套件:

public static Test suite() {
    TestSuite suite = new TestSuite("Some test collection");
    suite.addTestSuite(TestX.class);
    return suite;
}

在 JUnit4 中有等效的方法吗?

谢谢。

编辑

谢谢,我确实设法让它工作了。我的问题是,是否有 JUnit4 等效的方式来指定测试套件的名称/描述,例如在 JUnit3 中使用“一些测试集合”。

一些背景: 我正在将遗留代码中的 junit 测试转换为版本 4,如果可能的话,我不想丢失任何信息。抱歉,我真的应该在最初的问题中更具体。

【问题讨论】:

  • @RunWith(Suite.class) 不就是为了这个目的吗?
  • 是的,这是我用的。我只是没有找到将测试套件名称设置为默认字符串的方法,就像在 JUnit 3 中一样。我已经编辑了这个问题,因为回想起来我确实过于模糊了。

标签: junit junit4


【解决方案1】:

您可以使用Suite runner @RunWith(Suite.class) 来做到这一点:

@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class, TestX.class})
public class MySuite {}

其中Test1Test2TestX 包含您的测试

参考。 RunWith, Suite

更新:

WRT 更改套件的实际描述,我认为没有办法开箱即用(如果有的话,我还没有看到)。您可以做的是使用自定义描述 [update2] 定义您自己的跑步者:

@RunWith(DescribedSuiteRunner.class)
@SuiteClasses({Test1.class, Test2.class, TestX.class})
@SuiteDescription("Some test collection")
public class MySuite {}

public class DescribedSuiteRunner extends Suite {
    // forward to Suite
    public DescribedSuiteRunner(Class<?> klass, RunnerBuilder builder)
            throws InitializationError {
        super(klass, builder);
    }

    @Override
    protected String getName() {
        return getTestClass()
                .getJavaClass()
                .getAnnotation(SuiteDescription.class)
                .value();
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SuiteDescription {
    String value();
}

getName 的默认实现只返回被测试类的名称

【讨论】:

    【解决方案2】:

    是的,在 JUnit 3.x 中,必须专门命名 JUnit 方法。他们需要以单词 test 开头,以便 JUnit 将其作为测试用例运行。现在你可以使用@Test 注解了:

    @Test
    public void thisIsMyTest() {
        // test goes here
    }
    

    同样在 JUnit4 中,您可以声明是否希望在 beforeafter 调用此类中的所有测试:

    @Before
    public void init() throws Exception {
        System.out.println("Initializing...");
    }
    
    @After
    public void finish() throws Exception {
        System.out.println("Finishing...");
    }
    

    进一步比较 JUnit3 和 JUnit4 herehere

    编辑:在 blgt 发表评论后,我知道我可能误解了您的意图。 您正在可能正在寻找@RunWith(Suite.class) - 当一个类被@RunWith 注释时,JUnit 将调用被注释的类以运行测试,而不是使用 JUnit 中内置的运行器.完整的用法示例是here,tl;dr 下面:

    @RunWith(Suite.class)
    @SuiteClasses({ FirstTest.class, SecondTest.class })
    public class AllTests {
        ...
    }
    

    【讨论】:

    • 谢谢,虽然我的意思是试图找到一种方法来命名测试套件本身,就像在示例中一样。抱歉,我已经编辑了上面的问题。
    猜你喜欢
    • 2010-10-02
    • 1970-01-01
    • 2011-03-02
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多