Testng - 如果测试方法失败,如何使 AfterClass 方法失败?
Testng - How to fail AfterClass method if a test method fails?
如果之前有任何失败,我希望 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");
}
}
您可以使用 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();
}
}
}
}
如果之前有任何失败,我希望 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");
}
}
您可以使用 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();
}
}
}
}