Testng 测试后清除覆盖的testContext值
我扩展了TestListenerAdapter并添加了自己的自定义testName值。这特别适用于有数据提供程序且使用数据提供程序值设置名称的用例 以下是侦听器的外观:Testng 测试后清除覆盖的testContext值,testng,integration-testing,junit5,testng-dataprovider,Testng,Integration Testing,Junit5,Testng Dataprovider,我扩展了TestListenerAdapter并添加了自己的自定义testName值。这特别适用于有数据提供程序且使用数据提供程序值设置名称的用例 以下是侦听器的外观: public class CustomListener extends TestListenerAdapter { @Override public void onTestSuccess(final ITestResult tr) { setTestNameInReport(tr);
public class CustomListener extends TestListenerAdapter {
@Override
public void onTestSuccess(final ITestResult tr) {
setTestNameInReport(tr);
super.onTestSuccess(tr);
}
@Override
public void onTestFailure(final ITestResult tr) {
setTestNameInReport(tr);
super.onTestSuccess(tr);
}
private void setTestNameInReport(final ITestResult tr) {
try {
ITestContext ctx = tr.getTestContext();
Set<String> attributes = ctx.getAttributeNames();
for ( String x : attributes ) {
if (x.contains("testName")) {
Field method = TestResult.class.getDeclaredField("m_method");
System.out.println("Printing the method name: " + method.getName());
method.setAccessible(true);
method.set(tr, tr.getMethod().clone());
Field methodName = BaseTestMethod.class.getDeclaredField("m_methodName");
methodName.setAccessible(true);
methodName.set(tr.getMethod(), ctx.getAttribute( x ));
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
公共类CustomListener扩展TestListenerAdapter{
@凌驾
公开测试成功(最终测试结果tr){
setTestNameInReport(tr);
super.onTestSuccess(tr);
}
@凌驾
测试失败导致的公共无效(最终ITestResult tr){
setTestNameInReport(tr);
super.onTestSuccess(tr);
}
专用void setTestNameInReport(最终ITestResult tr){
试一试{
ITestContext ctx=tr.getTestContext();
Set attributes=ctx.getAttributeNames();
用于(字符串x:属性){
如果(x.contains(“testName”)){
Field method=TestResult.class.getDeclaredField(“m_方法”);
System.out.println(“打印方法名:“+method.getName()”);
方法setAccessible(true);
set(tr,tr.getMethod().clone());
FieldMethodName=BaseTestMethod.class.getDeclaredField(“m_methodName”);
methodName.setAccessible(true);
methodName.set(tr.getMethod(),ctx.getAttribute(x));
打破
}
}
}
捕获(例外e){
e、 printStackTrace();
}
}
}
我正在测试用例中设置testName
但是,很少有没有数据提供程序和不需要任何自定义测试名称的情况,如何清除测试上下文值?您可以使用
ITestContext
的removeAttribute()
方法。这样代码看起来就像:
@AfterMethod()
公共无效clearContext(ITestContext上下文){
removeAttribute(“testName”);
}
我们实际上需要使用上述方法将其从testResult实例中删除。if(tr.getTestContext().getAttribute(TEST_NAME)!=null){tr.getTestContext().removeAttribute(TEST_NAME);}