在哪里初始化TestNG TestContext



我有一个TestRunner类,它像这样启动我的TestNG:

TestRunConfigs configs = TestRunConfigs.parseCommandLine(args);
TestNG testRunner=new TestNG();
testRunner.setXmlSuites(getXmlSuites(configs.TestSuites));
testRunner.run();

我需要为我所有套件中的所有测试提供一些值。我认为ITestContext就是这样写的。我只是不知道该在哪里做。有路吗?

注意:请确保您使用的是TestNG 7.0.0-beta1,这是截至今天的最新发布版本

实现这一点的最简单方法是通过侦听器注入这些参数。

您基本上使用一个类来实现org.testng.ITestListener接口。您可以通过传入测试所需的自定义对象映射来实例化此侦听器。在侦听器onStart(ITestContext ctx)方法中,将这些属性传递给ITestContext对象。

下面是一个完整的例子,在实际操作中展示了这一点。

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.Reporter;
import org.testng.TestNG;
import org.testng.annotations.Test;
public class Example {
public static void main(String[] args) {
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] {MyTestClass.class});
Map<String, Data> attributes = new HashMap<>();
attributes.put("data1", new Data("TestNG"));
attributes.put("data2", new Data("Selenium"));
attributes.put("data3", new Data("Maven"));
LocalListener listener = new LocalListener(attributes);
testng.addListener(listener);
testng.setVerbose(2);
testng.run();
}
public static class LocalListener implements ITestListener {
private Map<String, Data> attributes;
public LocalListener(Map<String, Data> attributes) {
this.attributes = attributes;
}
@Override
public void onStart(ITestContext context) {
attributes.forEach(context::setAttribute);
}
}
public static class MyTestClass {
@Test
public void testMethod() {
ITestContext ctx = Reporter.getCurrentTestResult().getTestContext();
Set<String> attributeNames = ctx.getAttributeNames();
attributeNames.forEach(
attributeName -> {
System.err.println("===>" + ctx.getAttribute(attributeName).toString());
});
}
}
public static class Data {
private String name;
public Data(String name) {
this.name = name;
}
@Override
public String toString() {
return "Data[" + name + "]";
}
}
}

输出如下

===>Data[Maven]
===>Data[Selenium]
===>Data[TestNG]
PASSED: testMethod
===============================================
Command line test
Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Command line suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

最新更新