【问题标题】:Should JUnit ParentRunner catch AssertionError?JUnit ParentRunner 是否应该捕获 AssertionError?
【发布时间】:2015-09-03 07:10:35
【问题描述】:

我已经实现了一个基于BlockJUnit4ClassRunner 的自定义TestRunner。

我的假设是,任何失败的断言(表明产品/需求问题)都将通过addFailedAssumption() 报告给通知者,而其他异常将通过addFailure() 报告,表明单元测试本身存在错误。

查看结果,addFailedAssumption() 从未被调用过。在ParentRunner.runLeaf()的源码中,我看到了

try {
    statement.evaluate();
} catch (AssumptionViolatedException e) {
    eachNotifier.addFailedAssumption(e);
} catch (Throwable e) {
    eachNotifier.addFailure(e);
} finally {
    eachNotifier.fireTestFinished();
}

我得到的异常都是java.lang.AssertionError类型的。

ParentRunner应该追AssertionError还是我这边有误会?

【问题讨论】:

    标签: java unit-testing junit4


    【解决方案1】:

    阅读有关此主题的更多信息,这似乎是我这边的语言/翻译问题,因为我不是母语人士。

    找到课程 Assume 帮助我做对了(我希望),我会用一个例子来解释它:

    AssumtionViolatedException 的使用

    测试可以例如在不同的环境中运行,比方说不同的操作系统。也许产品在不同的操作系统上表现或需要表现略有不同,例如。因为它可以在较旧版本的操作系统中不存在的较新操作系统上使用 API 调用。这可能会导致类似

    的代码
    if(isApiPresent())
        SimpleAPICall();
    else
        // Do some crazy stuff here, potentially slower than the API call
    

    isApiPresent() 调用将根据操作系统返回不同的结果,因此您编写 2 个单元测试并添加关于环境的假设:

    @Test
    public void isApiPresent_returns_true_on_Win8()
    {
        assumeTrue(System.getProperty("os.version").equals("6.2"));
        assertTrue(isApiPresent());
    }
    @Test
    public void isApiPresent_returns_false_on_Win7()
    {
        assumeTrue(System.getProperty("os.version").equals("6.1"));
        assertFalse(isApiPresent());
    }
    

    如果没有给出关于操作系统的假设,由于@Test 注释,测试仍然会被执行,但它实际上应该被忽略。 assume...() 语句负责处理这一点:它们抛出一个 AssumptionViolatedException 可用于忽略测试。

    Eclipse 使用忽略图标标记违反假设的测试(尝试assumeFalse(true);):

    AssertionError 的使用

    我想通过自定义实现 TestRunner 实现的目标有点不同。我想找出哪些单元测试由于需求问题而失败,哪些测试由于其他异常而失败,这些异常可能表明单元测试本身存在错误,并在 Eclipse 中重建图标。 Eclipse 已经区分了这两种问题:AssertionErrors 用蓝色图标标记,Exceptions 用红色图标标记。

    对我来说,这意味着我必须执行fireTestFailure()中的决定:

    public void fireTestFailure(Failure failure) {
        originalNotifier.fireTestFailure(failure);
    
        if (failure.getException().getClass() == AssertionError.class) {
            // Requirement issue
        } else {
            // Unit test issue
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多