如何在@AfterMethod 中将@Test 标记为失败
How to mark @Test as failed in @AfterMethod
我正在尝试找出一种方法,如果 TetstNG 中有任何方法可以将用 @Test
注释的测试方法标记为在 @AfterMethod
.
中失败
@Test
public void sampleTest() {
// do some stuff
}
@AfterMethod
public void tearDown() {
// 1st operation
try {
// some operation
} catch(Exception e) {
// mark sampleTest as failed
}
// 2nd operation
try {
// perform some cleanup here
} catch (Exception e) {
// print something
}
}
我在所有测试中都要做一些验证,我在 tearDown()
的第一个 try-catch
块下进行。如果该块中存在异常,则将测试标记为失败。然后继续下一个try-catch
块。
我无法反转 tearDown()
中 try-catch 块的顺序,因为第一个块依赖于第二个块。
据我所知,您不能在 @AfterMethod
配置方法中执行此操作,因为传递给您的配置方法的 ITestResult 对象 [是的,您可以通过添加来访问测试方法的结果对象您的 @AfterMethod
注释方法的参数 ITestResult result
未用于更新原始测试方法的结果。
但是如果您要利用 IHookable
界面,您可以轻松地做到这一点。
您可以参考官方文档 here.
了解更多关于 IHookable
的信息
下面是一个演示此操作的示例。
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.Test;
public class TestClassSample implements IHookable {
@Test
public void testMethod1() {
System.err.println("testMethod1");
}
@Test
public void failMe() {
System.err.println("failMe");
}
@Override
public void run(IHookCallBack callBack, ITestResult result) {
callBack.runTestMethod(result);
if (result.getMethod().getMethodName().equalsIgnoreCase("failme")) {
result.setStatus(ITestResult.FAILURE);
result.setThrowable(new RuntimeException("Simulating a failure"));
}
}
}
注意:我正在使用 TestNG 7.0.0-beta7
(截至今天的最新发布版本)
我正在尝试找出一种方法,如果 TetstNG 中有任何方法可以将用 @Test
注释的测试方法标记为在 @AfterMethod
.
@Test
public void sampleTest() {
// do some stuff
}
@AfterMethod
public void tearDown() {
// 1st operation
try {
// some operation
} catch(Exception e) {
// mark sampleTest as failed
}
// 2nd operation
try {
// perform some cleanup here
} catch (Exception e) {
// print something
}
}
我在所有测试中都要做一些验证,我在 tearDown()
的第一个 try-catch
块下进行。如果该块中存在异常,则将测试标记为失败。然后继续下一个try-catch
块。
我无法反转 tearDown()
中 try-catch 块的顺序,因为第一个块依赖于第二个块。
据我所知,您不能在 @AfterMethod
配置方法中执行此操作,因为传递给您的配置方法的 ITestResult 对象 [是的,您可以通过添加来访问测试方法的结果对象您的 @AfterMethod
注释方法的参数 ITestResult result
未用于更新原始测试方法的结果。
但是如果您要利用 IHookable
界面,您可以轻松地做到这一点。
您可以参考官方文档 here.
IHookable
的信息
下面是一个演示此操作的示例。
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.Test;
public class TestClassSample implements IHookable {
@Test
public void testMethod1() {
System.err.println("testMethod1");
}
@Test
public void failMe() {
System.err.println("failMe");
}
@Override
public void run(IHookCallBack callBack, ITestResult result) {
callBack.runTestMethod(result);
if (result.getMethod().getMethodName().equalsIgnoreCase("failme")) {
result.setStatus(ITestResult.FAILURE);
result.setThrowable(new RuntimeException("Simulating a failure"));
}
}
}
注意:我正在使用 TestNG 7.0.0-beta7
(截至今天的最新发布版本)