stuXnet
stuXnet

Reputation: 4349

How can I fail a test in TestNG in an AfterMethod?

I want to check some external log files after each test, if there were ary errors during execution. Throwing an exception in an AfterMethod doesn't work, because it is handled differently by TestNG: it will just fail the configuration method and not the preceding test.

My approach would be like this:

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

    // doing other cleanUp-tasks
}

But still, my Eclipse TestNG plugin says the test passed.

Is it possible (and how) to fail a test (and not only a configuration method) in a configuration method?

Upvotes: 2

Views: 3479

Answers (2)

Jean Pierre
Jean Pierre

Reputation: 11

This might be too late but I can help anyone else who is looking for this.

You can do this using the ITestContext

For some reason you cant really update a result which is already generated. The workaround is to add the same result, remove it, update it then add it again. The only way I have found to remove a result is to do the add and remove sequence.

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)

I am using Groovy.

Upvotes: 1

Vlad.Bachurin
Vlad.Bachurin

Reputation: 1358

Try setCurrentTestResult() method from class org.testng.Reporter:

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

Upvotes: 2

Related Questions