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

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

我的方法是这样的:

 @AfterMethod(alwaysRun = true) protected void tearDown(ITestResult result) { if (thereWasAProblemDuringTestExecution()) { result.setStatus(ITestResult.FAILURE); result.setThrowable(getSomeThrowableSomebodyStoredAnywhere()); } // doing other cleanUp-tasks } 

但是,我的Eclipse TestNG插件仍然表示测试通过了。

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

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

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

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

您可以使用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。