2017-11-07 4 views
0

テストクラスを含むjarを指すことによって、TestNGテストをプログラムで実行します。このために、まずtestng.xmlが解析され、クラスが取得されます。その後、各クラスはURLCLassLoaderを使用してクラスパスにロードされます。しかし、これはorg.testng.TestNGException: Cannot find class in classpath:例外をスローします。以下は 外部JARを指すことによってプログラムでtestNGを実行するClassNotFoundException

は、私はあなたがするURLClassLoaderを使用してクラスローダをロードしている

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); 
    } 
} 

答えて

0

をしようとしたコードですが、あなたのクラスローダによってロードされたクラスは、現在のContextualClassLoaderに見えるようにするために、あなたが設定する必要がありますそれをアップ。

お客様のloadClass()メソッド内でThread.currentThread().setContextClassLoader();で試してみてから、テストを実行してください。これにより、TestNGが起動するときに、現在のスレッドに注入したContextClassLoaderを使用してクラスをロードして、クラスをロードするために使用することができます。ClassNotFoundException

+0

このContextClassloaderとから既存のクラスを削除しないのでしょう? –

+0

クラスローダーをURLクラスの親として設定しているため、クラスローダーを次のようにインスタンス化すると、 'URLClassLoader classLoader = new URLClassLoader(new URL [] {url}、ClassLoader.getSystemClassLoader());ローダ。 –

0

jarからテストを実行する場合それらをパッケージ化してxmlを使用して実行することができます。
testng documentationのコマンドラインセクションを参照してください。あなたは、Mavenプロジェクトである場合

は、これらのstepsを参照できます。

関連する問題