Maven 3和JUnit 4编译问题:包org.junit不存在

Are*_*sby 74 junit junit4 junit3 maven-3 maven

我正在尝试使用Maven构建一个简单的Java项目.在我的pom文件中,我声明JUnit 4.8.2是唯一的依赖项.仍然Maven坚持使用JUnit版本3.8.1.我如何解决它?

问题表现在编译失败:"package org.junit不存在".这是因为我的源代码中的import语句.JUnit 4.*中的正确包名称是org.junit.*,而在版本3中.*它是junit.framework.*

我想我已经在http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html找到了关于问题根源的文档,但是那里的建议似乎是Maven专家的意思.我不明白该怎么做.

Ren*_*tti 48

只是为了帮助访问者获得完整解决方案的答案:

您需要做的就是添加junit依赖项pom.xml.别忘了<scope>test</scope>

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

  • 是的,你的 junit 的版本很重要。我将其从 3.8.1 升级到 4.11,它解决了我的问题。 (2认同)

Are*_*sby 43

@Dennis Roberts:你说得对:我的测试类位于src/main/java中.此外,JUnit的POM中"scope"元素的值是"test",尽管它应该是这样的.问题是我在Eclipse中创建测试类时一直很邋,导致它在src/main/java中创建src/test/java.在运行"mvn eclipse:eclipse"之后,在Eclipse的Project Explorer视图中更容易看到这一点,但是您的评论是让我首先看到它的原因.谢谢.


oak*_*oak 18

我的问题是我内的线路pom.xml,我不得不行<sourceDirectory>${basedir}/src</sourceDirectory>删除此行取得的Maven使用普通的文件夹结构,解决了我的问题


小智 13

删除pom.xml中的范围标记以便junit工作..

  • 该解决方案是坏的,因为现在您发送您的JUnit测试类到您的督促二进制文件. (3认同)

Ste*_*360 5

我有同样的问题。我所做的只是 - 从 pom.xml 文件中,我删除了 junit 3.8 的依赖项,并为 junit 4.8 添加了一个新的依赖项。然后我做了 maven clean 和 maven install。它做到了。为了验证,在 maven 安装之后,我转到了项目-> 属性-构建路径-> Maven 依赖项,看到现在 junit 3.8 jar 不见了!,而是列出了 junit 4.8 jar。凉爽的!!。现在我的测试运行起来就像一个魅力..希望这有帮助..


tok*_*khi 5

将此依赖项添加到您的pom.xml文件中:

http://mvnrepository.com/artifact/junit/junit-dep/4.8.2

<!-- https://mvnrepository.com/artifact/junit/junit-dep -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit-dep</artifactId>
    <version>4.8.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)