我必须使用动态 testng.xml 文件执行测试脚本,这意味着我必须通过代码创建 testng.xml 文件并将参数传递给@Test方法以编程方式。
为此,我创建了两个Java文件 DynamicTestNG.java ,它们应生成 testng.xml 文件并运行 SampleClass.java ,其中@测试方法已与参数一起编写。
DynamicTestNG.java
[DllImport("WinCom32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern uint OpenRequest(out IntPtr hComs, string host, uint fBlockingMode, uint fOpenMode, uint fDataType, IntPtr hInstance);
static void Main(string[] args)
{
IntPtr hComs = new IntPtr();
uint test_Request = 0;
string hostName = ConfigurationManager.AppSettings["HostName"];
IntPtr hInstance = Marshal.GetHINSTANCE(Assembly.GetEntryAssembly().GetModules()[0]);
test_Request = OpenRequest(out hComs, hostName, 0, 0, 1, hInstance);
Console.WriteLine("Request response value: " + test_Request.ToString());
}
}
SampleClass.java
public class DynamicTestNG {
public void runTestNGTest(Map<String,String> testngParams) {
//Create an instance on TestNG
TestNG myTestNG = new TestNG();
//Create an instance of XML Suite and assign a name for it.
XmlSuite mySuite = new XmlSuite();
mySuite.setName("MySuite");
//Create an instance of XmlTest and assign a name for it.
XmlTest myTest = new XmlTest(mySuite);
myTest.setName("MyTest");
//Add any parameters that you want to set to the Test.
myTest.setParameters(testngParams);
//Create a list which can contain the classes that you want to run.
List<XmlClass> myClasses = new ArrayList<XmlClass> ();
myClasses.add(new XmlClass("SampleClass"));
//Assign that to the XmlTest Object created earlier.
myTest.setXmlClasses(myClasses);
//Create a list of XmlTests and add the Xmltest you created earlier to it.
List<XmlTest> myTests = new ArrayList<XmlTest>();
myTests.add(myTest);
//add the list of tests to your Suite.
mySuite.setTests(myTests);
//Add the suite to the list of suites.
List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
mySuites.add(mySuite);
//Set the list of Suites to the testNG object you created earlier.
myTestNG.setXmlSuites(mySuites);
TestListenerAdapter tla = new TestListenerAdapter();
myTestNG.addListener(tla);
//invoke run() - this will run your class.
myTestNG.run();
}
public static void main (String args[])
{
DynamicTestNG dt = new DynamicTestNG();
//This Map can hold your testng Parameters.
Map<String,String> testngParams = new HashMap<String,String> ();
testngParams.put("searchtext1", "testdata1");
testngParams.put("searchtext2", "testdata2");
dt.runTestNGTest(testngParams);
}
它没有运行。请告诉我这里的错误。
答案 0 :(得分:2)
您必须在 SampleClass 文件中取消注释@Test注释。如果您的SampleClass在一个包中,则在此语句中指定绝对包名+类名。
myClasses.add(new XmlClass("com.some.package.SampleClass"));
通常,TestNG类具有标记为“Test”的后缀或前缀,以便surefire插件可以将它们包含在执行流程中,以防您使用 maven 。
答案 1 :(得分:0)
您可以改为将构造函数与类object的参数一起使用。
myClasses.add(new XmlClass(SampleClass.class));