![](/img/trans.png)
[英]javassist throws ClassNotFoundException when loading external classes from jar
[英]Running testNG programmatically by pointing to an external jar throws ClassNotFoundException
我想通過指向包含測試類的jar來以編程方式運行TestNG測試。 為此,首先解析testng.xml並獲取類。 然后,使用URLCLassLoader
將每個類加載到類路徑中。 但這會引發org.testng.TestNGException: Cannot find class in classpath:
異常中org.testng.TestNGException: Cannot find class in classpath:
。
下面是我嘗試的代碼
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);
}
}
您正在使用URLClassLoader加載類加載器,但是要使您的類加載器加載的類對當前ContextualClassLoader可見,您需要對其進行設置。
請嘗試通過Thread.currentThread().setContextClassLoader();
在loadClass()
方法中,然后嘗試運行測試。 這樣可以確保當TestNG啟動時,它將使用您注入到當前線程中的ContextClassLoader
來加載類,從而幫助您克服ClassNotFoundException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.