Skip to main content

How to set up a Java project with Maven and JUnit

Set up a Java project with Maven: generate the project, declare JUnit 5 in the POM, write a class and a test, run tests with mvn test, and package with mvn package.

Difficulty
Beginner
Duration
40 minutes
Steps
6

What Maven and JUnit give you

Maven is a build and dependency management tool for the JVM. It defines a project through a pom.xml file, downloads dependencies from central repositories, and runs a standard build lifecycle. JUnit 5 is the standard Java testing framework. Together they provide a conventional, repeatable Java workflow.

Prerequisites

  • JDK 17 or later
  • Maven installed
  • A terminal

Steps

1. Generate a Maven project

Use the archetype generator to scaffold a standard layout.

mvn archetype:generate -DgroupId=com.example -DartifactId=calc \
  -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
cd calc

2. Configure dependencies in the POM

Add JUnit 5 to pom.xml under dependencies with test scope.

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>5.10.2</version>
  <scope>test</scope>
</dependency>

3. Write a class to test

package com.example;

public class Calc {
    public int add(int a, int b) { return a + b; }
}

Place it under src/main/java/com/example.

4. Write a JUnit 5 test

Tests live under src/test/java.

package com.example;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class CalcTest {
    @Test
    void addsNumbers() {
        assertEquals(5, new Calc().add(2, 3));
    }
}

5. Run tests with Maven

mvn test

Maven compiles the code and runs the tests through the Surefire plugin.

6. Package the application

mvn package

This produces a JAR in the target directory after tests pass.

Verification

Run mvn test and confirm the build succeeds with the test passing. Change the expected value to a wrong number and confirm the build fails with a clear assertion error, then fix it.

Next Steps

Add parameterized tests with @ParameterizedTest, configure the Surefire plugin, add a code coverage plugin such as JaCoCo, and run mvn verify in continuous integration.

Prerequisites

  • JDK 17+ installed
  • Maven installed
  • Basic command line familiarity

Steps

  • 1
    Generate a Maven project
  • 2
    Configure dependencies in the POM
  • 3
    Write a class to test
  • 4
    Write a JUnit 5 test
  • 5
    Run tests with Maven
  • 6
    Package the application