Reputation: 2325
I want the AfterClass code to not run if there is any failure before it. That is, if a test fails, then AfterClass should not run. How do I achieve that ?
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");
}
}
Upvotes: 0
Views: 1248
Reputation: 895
You could use TestNG listeners to override the default behavior. For example, a very simple listener which could do that
@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();
}
}
}
}
Upvotes: 1