【问题标题】:JUnitCore run() method is not implicitly calling setUp() before each testJUnitCore run() 方法不会在每次测试之前隐式调用 setUp()
【发布时间】:2010-08-23 20:40:05
【问题描述】:

我正在使用 JUnitCore 的 run(junit.framework.Test test) 并传入 ClassName.suite() 为 JUnit 测试用例创建自定义测试运行器。我的测试运行,但是返回的结果是null。似乎对象没有在setUp() 方法中初始化,因为setUp() 显然从未被调用,即使使用@Before 注释也是如此。如果我实例化每个测试方法中所需的每个对象,测试就会成功。然而,这种方法很乏味,并且违背了拥有测试课程的目的。这种行为正常吗?是否有更好的 JUnit 测试运行器反映与 Eclipse 中的测试运行器相同的行为?谢谢。

这是跑步者的代码:

public class TestRunner
{
    Result res = new Result();
    String results = new String();
    JUnitCore runner = new JUnitCore();

    protected TestRunner()
    {
    }

    public String runReport(Test input)
    {
        System.out.println(input.toString());
        res = runner.run(input);
        String testClass = "Class: ";
        String testFailCt = "Failure Count: ";
        String testFalures = "Failures: ";
        String testRunCt = "Runs: ";
        String testRunTm = "Run Time: ";
        String testSuccess = "Success: ";
        String newln = "\n";
        results += testClass + input.getClass() + newln;
        results += testFailCt + res.getFailureCount() + newln;
        results += testFalures + newln;
        List<Failure> failures = res.getFailures();
        int i = 0;
        for (Failure x: failures)
        {
            i++;
            results += i +": " + x + newln;
        }
        results += testRunCt + res.getRunCount() + newln;
        results += testRunTm + res.getRunTime() + newln;
        results += testSuccess + res.wasSuccessful() + newln;
        return results;
    }
}

下面是从另一个类调用runReport() 方法的方式:

runner.runReport(TestClassName.suite());

我应该将什么传递给run(),以便在每次测试之前隐式调用setUp()?我知道通过套房不会这样做。因此,我只是更改了我的测试用例,以便在每个测试中实例化所有必要的对象。

【问题讨论】:

  • 你能显示一些代码吗?更容易理解您的意思或查看拼写错误,这有时是问题的原因。

标签: java unit-testing junit


【解决方案1】:

... setUp() 显然从未被调用过,即使使用了@Before 注释。

JUnit 版本 4 支持注释 - 我认为 junit.framework 表明您使用的是版本 3。 如果您使用 JUnit 3 TestRunner 运行 JUnit 4 测试,您可能会发现这些文章感兴趣:

JUnit Test Runner that creates tests just before running them

JUnit FAQ - 见“写作测试”段落。 3.

An early look at JUnit 4

祝你好运!

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 2012-10-11
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2016-01-09
    • 2018-12-04
    相关资源
    最近更新 更多