我尝试通过Java代码生成TestNG.xml,但是当我将其作为Java应用程序运行时它可以正常工作,但它没有单独生成XML文件。我可以知道为什么,代码可以正常运行,但无法生成Xml文件分开。
我的代码:
package Testcases;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class GenerateTestng
{
@SuppressWarnings("deprecation")
public void runTestNGTest() {
//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("Wepaythemaxx");
//Create a list which can contain the classes that you want to run.
List<XmlClass> myClasses = new ArrayList<XmlClass> ();
myClasses.add(new XmlClass("Testcases.FinalTest"));
//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)
{
GenerateTestng dt = new GenerateTestng();
dt.runTestNGTest();
}
}
我已经在上面附加了我的代码,请确认,如果我做错了,我无法弄清楚。
最佳答案
我创建了此方法来保存文件:
public void createXmlFile(String saveFilePath, XmlSuite suiteName) {
File file = new File(saveFilePath);
FileWriter writer = null;
try {
writer = new FileWriter(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.write(suiteName.toXml());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(suiteName.toXml());
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
哪里
saveFilePath =文件保存路径,例如'.testNGxml.xml'
suiteName =您的套房名称,在您的情况下为mySuite