【问题标题】:How to programmatically execute a test suite using JUnit4?如何使用 JUnit4 以编程方式执行测试套件?
【发布时间】:2012-04-25 00:06:13
【问题描述】:

我正在尝试使用 API 调用 JUnit 测试套件。我知道您可以使用以下方法来设置测试类:

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

但是,有没有办法使用 Java API 来触发整个套件,例如使用 JUnitCore?

例如,您可以使用以下代码触发测试:

Runner r = 
try {
  r = new BlockJUnit4ClassRunner(Class.forName(testClass));
} catch (ClassNotFoundException | InitializationError e) {
  // handle
}
JUnitCore c = new JUnitCore();
c.run(Request.runner(r));

更新:

从 API 看来,Suite 类本身就是一个运行器,因此以下代码似乎可以工作:

Suite suite = new Suite(klass, new RunnerBuilder() {
... // Implement methods
});
JUnitCore c = new JUnitCore();
c.run(Request.runner(suite));

但我不确定这是否是推荐的方法,或者编写上述代码是否有任何缺点。

【问题讨论】:

    标签: junit automated-tests junit4 test-suite


    【解决方案1】:

    只需将套件类的名称指定给 JUnitCore:

    Computer computer = new Computer();
    
    JUnitCore jUnitCore = new JUnitCore();
    jUnitCore.run(computer, MySuite.class);
    

    【讨论】:

    • 谢谢马修!我一定会试一试的。同时,您对我更新中的代码 sn-p 有什么建议吗?
    【解决方案2】:

    你也可以使用命令提示符作为

    java org.junit.runner.JUnitCore 测试类名

    【讨论】:

    • 我认为这不符合“程序化”的条件。
    • 如果你使用 runtime.exec 调用它会这样
    猜你喜欢
    • 1970-01-01
    • 2019-01-28
    • 2020-07-14
    • 2017-10-02
    • 2021-01-09
    • 2011-12-06
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多