Testng-如果测试方法失败,如何使AfterClass方法失败?

时间:2019-11-14 20:56:41

标签: java testng

如果在出现任何故障之前,我希望AfterClass代码不运行。也就是说,如果测试失败,则AfterClass不应该运行。我该如何实现?

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Testing {
    @BeforeClass
    public void b4class(){
        System.out.println("b4class");
    }

    @Test
    public void t1(){
        System.out.println("t1");
        throw new IllegalArgumentException("BOOM");
    }

    @AfterClass(alwaysRun = false)
    public void afterClass(){
        System.out.println("afterClass");
    }

}

1 个答案:

答案 0 :(得分:1)

您可以使用TestNG listeners覆盖默认行为。例如,一个非常简单的侦听器可以做到这一点

@Listeners({Testing.MethodInterceptor.class})
public class Testing {

    @BeforeClass
    public void b4class(){
        System.out.println("b4class");
    }

    @Test
    protected void t1(){
        System.out.println("t1");
        throw new IllegalArgumentException("BOOM");
    }

    @AfterClass
    public void afterClass(){
        System.out.println("afterClass");
    }

    public static class MethodInterceptor implements IInvokedMethodListener {

        int status = ITestResult.SUCCESS;

        @Override
        public void beforeInvocation(final IInvokedMethod method, final ITestResult testResult) {
            if (method.isConfigurationMethod()
                    && method.getTestMethod().getMethodName().equals("afterClass")
                    && ITestResult.FAILURE == status) {
                throw new IllegalStateException("BIG BOOM");
            }
        }

        @Override
        public void afterInvocation(final IInvokedMethod method, final ITestResult testResult) {
            if (method.getTestMethod().getMethodName().equals("t1")) {
                status = testResult.getStatus();
            }
        }
    }
}