问题
I'm trying to create a JAR that I can put on a non development machine and run some unit tests that exercise a web service. I've read that there are many ways to do this in maven. I'm focusing on using the test-jar goal because that seems the most logical approach.
My tests are in a separate maven project with a folder structure of:
/myProject/src/test/java/org/testplatform/services/test/<name of testng test>.java
Here is my config for the test-jar in the pom:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>org/testplatform/services/test/MainTestClass.java</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
When I execute the resulting JAR I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/testng/ITestListener
Caused by: java.lang.ClassNotFoundException: org.testng.ITestListener
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Can someone help me understand what changes I need to make in my pom and/or tests to create an independent, executable JAR for running testng unit tests? A demo project would be helpful.
回答1:
The error is suggesting that you are using TestNG classes and that these aren't available in the resulting classpath. This is possible because you test
scoped your testNG dependency
<dependency>
<groupId>...</groupId>
<artifactId>...</artifactId>
<version>...</version>
<scope>test</scope> <<< Test scope
</dependency>
This will result in the exclusion of this dependency from the resulting JAR.
In case you haven't already, I suggest reading Maven's in-depth explanation of the recommended way of building a test JAR and the pitfalls to avoid.
You have the made the correct step of extracting your test classes to a separate project. This ensures that you can leverage Maven's transitive dependencies. You also need to move dependencies out of test scope.
来源:https://stackoverflow.com/questions/8317147/error-when-creating-an-executable-test-jar-in-maven