テストクラスを含むjarを指すことによって、TestNGテストをプログラムで実行します。このために、まずtestng.xmlが解析され、クラスが取得されます。その後、各クラスはURLCLassLoader
を使用してクラスパスにロードされます。しかし、これはorg.testng.TestNGException: Cannot find class in classpath:
例外をスローします。以下は 外部JARを指すことによってプログラムでtestNGを実行するClassNotFoundException
public void execute() {
String testNGXmlPath = "/path/to/testng.xml";
try {
getClassesToLoad(testNGXmlPath);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
TestNG testng = new TestNG();
List<String> suites = Lists.newArrayList();
suites.add(testNGXmlPath);
testng.setTestSuites(suites);
testng.run();
}
public void getClassesToLoad(String path) throws ParserConfigurationException, IOException, SAXException {
File inputFile = new File(path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("class");
Element element;
Node node;
NamedNodeMap namedNodeMap;
int i, length;
length = nodeList.getLength();
for (int j=0; j < length; j++) {
element = (Element)nodeList.item(j);
namedNodeMap = element.getAttributes();
if (namedNodeMap != null) {
for (i=0; i<namedNodeMap.getLength(); i++) {
node = namedNodeMap.item(i);
if (node.getNodeName() == "name") {
try {
loadClass("/path/to/testng.sample-1.0-SNAPSHOT.jar", node.getNodeValue());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
}
}
}
public static void loadClass(String jarFilePath, String className) throws MalformedURLException,
ClassNotFoundException {
File jarFile = new File(jarFilePath);
if (jarFile.isFile()) {
URL url = jarFile.toURL();
URL[] urls = new URL[] { url };
ClassLoader cl = new URLClassLoader(urls);
cl.loadClass(className);
}
}
このContextClassloaderとから既存のクラスを削除しないのでしょう? –
クラスローダーをURLクラスの親として設定しているため、クラスローダーを次のようにインスタンス化すると、 'URLClassLoader classLoader = new URLClassLoader(new URL [] {url}、ClassLoader.getSystemClassLoader());ローダ。 –