如何在AfterMethod中的TestNG测试失败?

时间:2013-12-13 15:09:01

标签: java testing testng

如果执行期间出现ary错误,我想在每次测试后检查一些外部日志文件。在AfterMethod中抛出异常不起作用,因为TestNG对它的处理方式不同:它只会使配置方法失败而不是前面的测试。

我的方法是这样的:

@AfterMethod(alwaysRun = true)
protected void tearDown(ITestResult result) {
    if (thereWasAProblemDuringTestExecution()) {
        result.setStatus(ITestResult.FAILURE);
        result.setThrowable(getSomeThrowableSomebodyStoredAnywhere());
    }

    // doing other cleanUp-tasks
}

但是,我的Eclipse TestNG插件说测试通过了。

配置方法中是否可能(以及如何)使测试失败(而不仅仅是配置方法)?

2 个答案:

答案 0 :(得分:2)

尝试使用org.testng.Reporter类中的setCurrentTestResult()方法:

result.setStatus(ITestResult.FAILURE);
Reporter.setCurrentTestResult(result);

答案 1 :(得分:1)

这可能为时已晚,但我可以帮助其他正在寻找此事的人。

您可以使用ITestContext

执行此操作

由于某种原因,您无法真正更新已生成的结果。解决方法是添加相同的结果,删除它,更新它然后再添加它。我发现删除结果的唯一方法是执行添加和删除序列。

def testContext = Reporter.currentTestResult.testContext
testContext.passedTests.addResult(result,Reporter.currentTestResult.method)
testContext.passedTests.getAllMethods().remove(Reporter.currentTestResult.method)
result.setStatus(ITestResult.FAILURE)
testContext.failedTests.addResult(result,Reporter.currentTestResult.method)

我正在使用Groovy。