Skip to content

TestNG – how to run the same method at the end of each test

I have something like:

@Test(priority = 1)
public void test1() {
    testSomething1();
    Assert.assertFalse(errorsExists());
}
    
@Test(priority = 2)
public void test2() {
    testSomething2();
    Assert.assertFalse(errorsExists());
}
    
@Test(priority = 3)
public void test3() {
    testSomething3();
    Assert.assertFalse(errorsExists());
}

and I would like to move Assert.assertFalse(errorsExists()) to BaseTestCase or to TestListener so I will not have to pass it every time at the end of the test. I tried to move it to TestsListener to onFinish but method errorsExists() requires driver and I have problems to get it in there.

Update: I want to method errorsExists() influence test result. Lets say that in test2 method errorsExists return true -> I want to have following results: test1 passed test2 failed test3 passed

so as far as I know I cannot put this method to any @After annotations and I cannot put it to onTestFailure or onTestSuccess in TestListener

Answer

You may use the IHookable interface to achieve this. This is usually (according to the documentation), used to do some operations before the test start. But it works fine for operations at the end of each test as well.

Create a BaseTest which implements this interface and let your test classes extend the BaseTest.

public class BaseTest implements IHookable {

    @Override
    public void run(IHookCallBack cb, ITestResult testResult) {
        cb.runTestMethod(testResult); // invokes the actual test case
        Assert.assertFalse(errorsExists());
    }
}