【问题标题】:Error when creating an executable test-jar in Maven在 Maven 中创建可执行的 test-jar 时出错
【发布时间】:2012-01-09 04:04:18
【问题描述】:

我正在尝试创建一个 JAR,我可以将它放在非开发机器上并运行一些运行 Web 服务的单元测试。我读过在 Maven 中有很多方法可以做到这一点。我专注于使用 test-jar 目标,因为这似乎是最合乎逻辑的方法。

我的测试在一个单独的 maven 项目中,其文件夹结构为:

/myProject/src/test/java/org/testplatform/services/test/<name of testng test>.java

这是我在 pom 中的 test-jar 的配置:

        <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>

当我执行生成的 JAR 时出现此错误:

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)

有人可以帮助我了解我需要在我的 pom 和/或测试中进行哪些更改以创建一个独立的、可执行的 JAR 来运行 testng 单元测试吗?一个演示项目会很有帮助。

【问题讨论】:

    标签: unit-testing maven jar testng executable-jar


    【解决方案1】:

    错误提示您正在使用 TestNG 类,并且这些类在生成的类路径中不可用。这是可能的,因为您 test 限定了您的 testNG 依赖项

    <dependency>
      <groupId>...</groupId>
      <artifactId>...</artifactId>
      <version>...</version>
      <scope>test</scope>           <<< Test scope
    </dependency>
    

    这将导致从生成的 JAR 中排除此依赖项。

    如果您还没有,我建议您阅读Maven's in-depth explanation,了解构建测试 JAR 的推荐方法以及要避免的陷阱。

    您已经完成了将测试类提取到单独项目的正确步骤。这确保您可以利用 Maven 的传递依赖关系。您还需要将依赖项移出测试范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-21
      • 2010-12-22
      • 2011-06-28
      • 2019-08-05
      • 2014-05-19
      • 2019-10-06
      • 2017-06-27
      • 2010-12-21
      相关资源
      最近更新 更多