Maven and JUnit example

In Maven, you can declare the JUnit dependency like this:

pom.xml

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

But, it comes with a bundled copy of hamcrest-core library.


$ mvn dependency:tree
...
[INFO] \- junit:junit:jar:4.12:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:test
...

1. Maven + JUnit + Hamcrest

Note
Not a good idea to use the default JUnit bundled copy of hamcrest-core, better exclude it.

Review the updated pom.xml again, it excludes the JUnit bundled copy of hamcrest-core. On the other hand, it also includes the useful hamcrest-library :

pom.xml

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.hamcrest</groupId>
					<artifactId>hamcrest-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- This will get hamcrest-core automatically -->
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

Review the dependency tree again.


$ mvn dependency:tree
...
[INFO] +- junit:junit:jar:4.12:test
[INFO] \- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:test
...

References

  1. How to create a Java project with Maven
  2. Maven – Display project dependency
  3. JUnit – Use with Maven

2 comments on “Maven and JUnit example

  1. Stating “Not a good idea to use ” without providing any reason makes your post bad because it gives the reader more open questions than it answers and wastes everybodies time. Thanks.

    Reply
  2. You did not mention why hamcrest-library is preferred over hamcrest-core?

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *