0
0
JUnittesting~5 mins

Maven dependency setup in JUnit

Choose your learning style9 modes available
Introduction

Maven dependency setup helps you add external libraries like JUnit to your project easily. It saves time and avoids manual downloads.

When you want to add JUnit to your Java project for writing tests.
When you need to manage library versions automatically.
When you want to share your project with others and keep dependencies consistent.
When you want to update or remove libraries without hassle.
Syntax
JUnit
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>5.9.3</version>
  <scope>test</scope>
</dependency>

The <scope>test</scope> means this library is only used during testing, not in the final app.

Always check for the latest version of JUnit on the official Maven repository.

Examples
This adds only the JUnit API for writing tests.
JUnit
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>5.9.3</version>
  <scope>test</scope>
</dependency>
This adds the engine to run JUnit tests.
JUnit
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.9.3</version>
  <scope>test</scope>
</dependency>
This adds the full JUnit Jupiter package for writing and running tests.
JUnit
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>5.9.3</version>
  <scope>test</scope>
</dependency>
Sample Program

This is a complete Maven pom.xml file that sets up JUnit 5.9.3 for testing. The Surefire plugin runs the tests.

JUnit
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>demo-test</artifactId>
  <version>1.0-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.9.3</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M7</version>
      </plugin>
    </plugins>
  </build>
</project>
OutputSuccess
Important Notes

Always place test dependencies inside the <dependencies> section.

Use the test scope to avoid including test libraries in your final build.

Run mvn clean test to compile and run tests using Maven.

Summary

Maven dependency setup adds libraries like JUnit automatically.

Use <dependency> tags inside pom.xml to add JUnit.

Set scope to test so libraries are only used during testing.