To write your first JUnit 5 test with Maven, add the junit-jupiter dependency with test scope, put a class under src/test/java, annotate a method with @Test, and run mvn test. Maven's Surefire plugin finds the test, runs it on the JUnit Platform and reports the result. This junit 5 first test maven walkthrough uses a small class and takes about five minutes.
You need a JDK (17 or newer is a sensible choice today; 21 and 25 are LTS releases) and Maven 3.9 or newer.
Maven expects a fixed directory structure:
Production code goes under src/main/java, tests under src/test/java. Keeping the test class in the same package as the class under test lets it use package-private members.
Three points matter here:
junit-jupiter is the aggregate artifact: the API, the engine and parameterized tests.<scope>test</scope> keeps JUnit out of your production artifact.Version numbers move on, so check Maven Central for the latest JUnit and Surefire releases.
Production code in Calculator.java:
The test in CalculatorTest.java:
The class and its methods can be package-private. JUnit creates a new instance of CalculatorTest for every test method, so the tests cannot affect each other through fields. The name of a test method is free; describe the behaviour, not the method under test.
assertEquals(expected, actual) takes the expected value first. assertThrows runs the lambda and passes only if it throws the given exception type.
From the project directory:
Surefire picks up classes whose names match patterns such as *Test, Test* and *Tests. The output ends with a summary like this:
To run one class or one method:
XML and text reports are written to target/surefire-reports. IDEs such as IntelliJ IDEA and Eclipse can also run the same class directly with a green arrow next to the test.
Change the expectation to a wrong value, for example assertEquals(6, calculator.add(2, 3)), and run mvn test again. JUnit prints the difference:
Always watch a new test fail once. A test that has never failed might not test anything.
The most common causes are an old Surefire plugin, a class name that does not match the Surefire patterns, or a missing junit-jupiter dependency. Update Surefire to 3.x and check the class name ends in Test.
No. In JUnit 5 the class and test methods can be package-private. They must not be private, and test methods must not be static.
No. Use org.junit.jupiter.api.Test. Mixing the two means the test is silently ignored by the Jupiter engine.
In src/test/resources, which Maven adds to the test classpath.
Add junit-jupiter with test scope, make sure Surefire is 3.x, place tests under src/test/java and mark methods with @Test. Use assertEquals and assertThrows to check results, run mvn test, and read the Surefire summary. Always see a new test fail once to prove it works.