Maven编译错误:找不到符号。

4

我真的不知道该怎么提出一个不同的问题标题……

我有三个Maven模块。第一个是父模块,只是将子模块包装起来。没有什么花里胡哨的东西。在第二个模块中,我有一个测试类,它是抽象的,并且有两个方法。

在第三个模块中,我有一个测试类,继承自第二个模块的抽象类。

当我尝试用Maven构建时,我会遇到编译错误,说找不到第二个模块的抽象类这个符号。有趣的是,在Eclipse中我没有遇到任何编译错误。

这是第三个模块的POM片段:

<dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>SecondModule</artifactId>
  <version>${project.version}</version>
</dependency>



</dependencies>
  <build>
    <defaultGoal>install</defaultGoal>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
      </plugin>

      <!-- to generate the MANIFEST-FILE of the bundle -->
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Import-Package>*</Import-Package>
            <Export-Package></Export-Package>
            <Embed-Dependency>SecondModule</Embed-Dependency>
          </instructions>
        </configuration>
      </plugin>

    </plugins>

我遇到的错误是:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project ThirdModule: Compilation failure: Compilation failure:
[ERROR] D:/workspace/project/ThirdModule/src/test/java/org/rrrrrrr/ssssss/thirdmodule/ConcreteTest.java:[7,56] cannot find symbol
[ERROR] symbol:   class AbstractTest
[ERROR] location: package org.rrrrrrr.ssssss.secondmodule

我错过了什么?

异常具体是什么? - Subodh Joshi
我将测试代码从项目中分离出来,放到另一个项目中,错误消失了。 - Izaias Dantas
1个回答

5

当您添加依赖项时,测试类(src/test内的类)不会自动添加到类路径中。只有在src/main中的类才会被包括。

要添加对测试类的依赖,您需要明确指定将类型指定为test-jar在依赖项部分。这应该是模块3的pom.xml中定义的依赖项。

<dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>SecondModule</artifactId>
  <version>${project.version}</version>
  <type>test-jar</type> <!-- add dependency to test jar -->
</dependency>

确保第二模块生成了测试包(test-jar)也是个好主意。因为需要编译第三模块的任何人都需要同时编译第二模块。默认情况下,maven不会将测试类打包成jar。要告诉maven这样做,需要在maven-jar-plugin执行中添加目标:jar和test-jar。这样原始jar和测试jar都将被生成。

以下是展示此功能的第二模块的pom.xml大纲。

<project>
  <build>
    <plugins>
     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-jar-plugin</artifactId>
       <executions>
         <execution>
           <goals>
             <goal>jar</goal>
             <goal>test-jar</goal>
           </goals>
         </execution>
       </executions>
     </plugin>
    </plugins>
  </build>
</project>

非常感谢。现在可以工作了。我没有意识到测试类没有添加到类路径中。 - lonely-sm-developer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接