Maven 3 and JUnit 4 compilation problem: package o

2019-01-16 22:30发布

I am trying to build a simple Java project with Maven. In my pom-file I declare JUnit 4.8.2 as the only dependency. Still Maven insists on using JUnit version 3.8.1. How do I fix it?

The problem manifests itself in a compilation failure: "package org.junit does not exist". This is because of the import statement in my source code. The correct package name in JUnit 4.* is org.junit.* while in version 3.* it is junit.framework.*

I think I have found documentation on the root of the problem on http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html but the advice there seems to be meant for Maven experts. I did not understand what to do.

16条回答
叛逆
2楼-- · 2019-01-16 23:03

Add this dependency to your pom.xml file:

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>
查看更多
成全新的幸福
3楼-- · 2019-01-16 23:05

I had a quite similar problem in a "test-utils" project (adding features, rules and assertions to JUnit) child of a parent project injecting dependencies. The class depending on the org.junit.rules package was in src/main/java.

So I added a dependency on junit without test scope and it solved the problem :

pom.xml of the test-util project :

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
</dependency>

pom.xml of the parent project :

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <scope>test</scope>
</dependency>
查看更多
▲ chillily
4楼-- · 2019-01-16 23:08

Find the one solution for this error if you have code in src/main/java Utils

<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.1</version>
</dependency>
查看更多
叛逆
5楼-- · 2019-01-16 23:11

By default , maven looks at these folders for java and test classes respectively - src/main/java and src/test/java

When the src is specified with the test classes under source and the scope for junit dependency in pom.xml is mentioned as test - org.unit will not be found by maven.

查看更多
登录 后发表回答