gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:18:03 26 4
gpt4 key购买 nike

如果 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();
}
}
}
}

关于java - Testng - 如果测试方法失败,如何使 AfterClass 方法失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com