Tests in the Maven build
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's tests only protect you if they run on every build. How does Maven find the tests, run them and stop a broken version from becoming a jar?
src/test/java mirrors src/main/java
src/test/java is the Maven folder for test code. It has the same package folders as src/main/java, its classes compile into target/test-classes, and they are never put in the jar.
ShopLite keeps main code and test code in two folder trees with the same package names. Only the main tree ends up in the jar.
shoplite-api/ src/main/java/com/shoplite/order/OrderItem.java -> target/classes -> in the jar src/main/resources/application.properties src/test/java/com/shoplite/order/OrderItemTest.java -> target/test-classes -> never in the jar src/test/resources/application-test.propertiesExample 1 · Test classes are not in the jar
Runs in: a terminal in the shoplite-api project after mvn package
jar tf target/shoplite-api-1.1.0.jar | grep -c "Test"jar tf target/shoplite-api-1.1.0.jar | grep "com/shoplite/order/OrderItem"ls target/test-classes/com/shoplite/order$ jar tf target/shoplite-api-1.1.0.jar | grep -c "Test" 0 $ jar tf target/shoplite-api-1.1.0.jar | grep "com/shoplite/order/OrderItem" BOOT-INF/classes/com/shoplite/order/OrderItem.class BOOT-INF/classes/com/shoplite/order/OrderItemRequest.class BOOT-INF/classes/com/shoplite/order/OrderItemResponse.class $ ls target/test-classes/com/shoplite/order OrderCancellationIT.class OrderControllerTest.class OrderOwnershipIT.class OrderServiceIT.class
What this code does
jar tflists the files inside the jar. No file name containsTest, andOrderItemis there underBOOT-INF/classes(where Spring Boot jars keep your classes).- The compiled tests exist only in
target/test-classes, which Maven uses while testing and never packages.
OrderItemTest in com.shoplite.order sits in the same package as OrderItem, so it can use its package-private methods.
Maven never puts test classes or test-only libraries, such as JUnit, in the jar. The application you ship contains only src/main.
The junit-jupiter dependency and the Surefire plugin
Surefire is the Maven plugin that runs unit tests in the test phase. It runs every class named Test, Tests, Test* or *TestCase, using the JUnit 5 engine from the junit-jupiter dependency.
This pom.xml adds JUnit 5 for tests only and names the Surefire plugin. The output shows mvn test running four tests.
Example 2 · A plain Maven project's pom.xml with JUnit 5 and Surefire
Runs in: a plain Maven project (no Spring Boot parent)
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.shoplite</groupId> <artifactId>shop-pricing</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.release>17</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.14.4</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.5.6</version> </plugin> </plugins> </build></project>$ mvn test ... [INFO] --- surefire:3.5.6:test (default-test) @ shop-pricing --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.shoplite.pricing.PriceCalculatorTest [INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.058 s -- in com.shoplite.pricing.PriceCalculatorTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
junit-jupiteris one dependency that pulls in the API, the parameterised-test support and the engine;<scope>test</scope>keeps it out of the main code and the jar.- Surefire detects the JUnit Platform by itself ("Using auto detected provider ... JUnitPlatformProvider") and runs every matching test class.
The junit-jupiter dependency brings the JUnit 5 API (@Test, assertEquals) and the engine that runs it. It uses <scope>test</scope>, so only test code sees it and it is never shipped.
In a plain Maven project you write the versions yourself: junit-jupiter 5.14.4 and Surefire 3.5.6, as in the Section 13 projects. In shoplite-api, Spring Boot 4.1.1 manages both: its test starters bring JUnit, AssertJ and Mockito, and Boot picks the versions (JUnit 6.0.3 at the time of writing, the next major version of the same Jupiter API, so every annotation in this section works the same). Do not pin them yourself there.
Find the bug
Fix the test setup
Each snippet has one line that stops tests from working properly. Tap it, then read the fix.
JUnit must be visible only to test code.
Round 1 of 3mvn test and the Surefire report
A failure means an assertion was false. An error means the test threw an unexpected exception, such as a NullPointerException. Both make Maven end with BUILD FAILURE.
Here mvn test runs in shoplite-api. Surefire prints one line per test class and a summary of the counts.
Example 3 · mvn test in shoplite-api and the report files
Runs in: a terminal in the shoplite-api project
mvn testls target/surefire-reports$ mvn test ... [INFO] --- surefire:3.5.6:test (default-test) @ shoplite-api --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.shoplite.auth.AuthControllerTest [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.660 s -- in com.shoplite.auth.AuthControllerTest [INFO] Running com.shoplite.auth.JwtPropertiesTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 s -- in com.shoplite.auth.JwtPropertiesTest [INFO] Running com.shoplite.order.OrderControllerTest [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.591 s -- in com.shoplite.order.OrderControllerTest [INFO] Running com.shoplite.product.ProductControllerTest [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.831 s -- in com.shoplite.product.ProductControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 20, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS $ ls target/surefire-reports TEST-com.shoplite.auth.AuthControllerTest.xml TEST-com.shoplite.auth.JwtPropertiesTest.xml TEST-com.shoplite.order.OrderControllerTest.xml TEST-com.shoplite.product.ProductControllerTest.xml com.shoplite.auth.AuthControllerTest.txt com.shoplite.auth.JwtPropertiesTest.txt com.shoplite.order.OrderControllerTest.txt com.shoplite.product.ProductControllerTest.txt
What this code does
- Surefire ran the four
*Testclasses (20 tests). Notice the times: the plain-classJwtPropertiesTesttakes 0.041 s, whileAuthControllerTesttakes 5.6 s because it starts part of Spring. The*ITclasses did not run here. - Each class gets a
.txtreport (read it when a test fails) and aTEST-...xmlreport for tools. Spring's log lines between the test lines are cut here with....
Example 4 · Reading a Surefire summary line in Java
public class SurefireSummaryDemo { record Summary(int run, int failures, int errors, int skipped) { boolean buildFails() { return failures > 0 || errors > 0; // skipped tests do not fail the build } }
// Reads "Tests run: 20, Failures: 0, Errors: 0, Skipped: 0" from a log line static Summary parse(String line) { String[] parts = line.substring(line.indexOf("Tests run:")).split(","); int[] n = new int[4]; for (int i = 0; i < 4; i++) { n[i] = Integer.parseInt(parts[i].split(":")[1].trim()); } return new Summary(n[0], n[1], n[2], n[3]); }
public static void main(String[] args) { String[] lines = { "[INFO] Tests run: 20, Failures: 0, Errors: 0, Skipped: 0", "[ERROR] Tests run: 4, Failures: 2, Errors: 0, Skipped: 0", "[ERROR] Tests run: 9, Failures: 0, Errors: 1, Skipped: 1", "[WARNING] Tests run: 6, Failures: 0, Errors: 0, Skipped: 2", }; for (String line : lines) { Summary s = parse(line); int passed = s.run() - s.failures() - s.errors() - s.skipped(); System.out.println(s + " -> passed " + passed + ", " + (s.buildFails() ? "BUILD FAILURE" : "BUILD SUCCESS")); } }}Summary[run=20, failures=0, errors=0, skipped=0] -> passed 20, BUILD SUCCESS Summary[run=4, failures=2, errors=0, skipped=0] -> passed 2, BUILD FAILURE Summary[run=9, failures=0, errors=1, skipped=1] -> passed 7, BUILD FAILURE Summary[run=6, failures=0, errors=0, skipped=2] -> passed 4, BUILD SUCCESS
What this code does
- "Tests run" counts every test, including failed and skipped ones, so the passed count is run minus failures, errors and skipped.
- A failure (a false assertion) and an error (an unexpected exception) both fail the build. Skipped tests do not, which is why skipping is dangerous: the build stays green while nothing is checked.
Besides the console lines, Surefire writes a report per class in target/surefire-reports: a .txt file with the failure and stack trace, and an .xml file that CI servers and IDEs read.
If you see Tests run: 0 or "No tests to run", the tests were not found. Check these four things:
- The class is in
src/test/java, notsrc/main/java. - The class name ends in
Test,TestsorTestCase, or starts withTest;OrderChecksis ignored. - The import is
org.junit.jupiter.api.Test; the old JUnit 4org.junit.Testis not run by the Jupiter engine. - The test method is not
private; JUnit does not run a private@Testmethod.
Predict the output
Read the Surefire summary
Work out the result from the counts.
Round 1 of 3
How many tests passed?
A failing test fails the build; running one test with -Dtest
-Dtest tells Surefire which tests to run: -Dtest=ClassName runs one class and -Dtest=ClassName#methodName runs one method. A pattern that matches nothing is an error.
While fixing one test you do not want to run them all. These commands run one class, one method, and a misspelt class name.
Example 5 · Running one class or one method with -Dtest
Runs in: a terminal in the shoplite-api project
mvn test -Dtest=JwtPropertiesTestmvn test -Dtest=JwtPropertiesTest#rejectsAShortKeymvn test -Dtest=JwtPropertyTest$ mvn test -Dtest=JwtPropertiesTest ... [INFO] Running com.shoplite.auth.JwtPropertiesTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 s -- in com.shoplite.auth.JwtPropertiesTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS $ mvn test -Dtest=JwtPropertiesTest#rejectsAShortKey ... [INFO] Running com.shoplite.auth.JwtPropertiesTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.038 s -- in com.shoplite.auth.JwtPropertiesTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS $ mvn test -Dtest=JwtPropertyTest ... [INFO] BUILD FAILURE [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.5.6:test (default-test) on project shoplite-api: No tests matching pattern "JwtPropertyTest" were executed! (Set -Dsurefire.failIfNoSpecifiedTests=false to ignore this error.)
What this code does
-Dtest=JwtPropertiesTestruns only that class, in well under a second instead of waiting for the controller tests. Adding#rejectsAShortKeynarrows it to one method. On Windows PowerShell, put the value in quotes:"-Dtest=JwtPropertiesTest#rejectsAShortKey".- The third command has a typo (
Propertyinstead ofProperties). Surefire fails instead of reporting a green build with zero tests.
When any test fails, Surefire ends with BUILD FAILURE and the later phases (package, install) do not run. That is the point: the jar is only built from code whose tests pass.
The typo in the third command fails the build instead of quietly running zero tests, which protects you from a green build that checked nothing.
Failsafe and *IT classes; why -DskipTests is a last resort
Failsafe is the Maven plugin that runs slower integration tests, the *IT classes, after the jar is built, in the integration-test phase. It fails the build in the verify phase.
In a plain Maven project, this plugin block makes mvn verify run the *IT classes.
<!-- Plain Maven project: run *IT classes in "mvn verify" --><plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>3.5.6</version> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions></plugin>Example 6 · Which plugin runs this class? Surefire and Failsafe name patterns
import java.util.List;
public class TestNamePatternsDemo { // Default include patterns, written as regular expressions on the simple class name static String pluginFor(String className) { if (className.matches("IT.*|.*IT|.*ITCase")) { return "Failsafe (mvn verify)"; } if (className.matches("Test.*|.*Test|.*Tests|.*TestCase")) { return "Surefire (mvn test)"; } return "nobody - never run"; }
public static void main(String[] args) { List<String> classes = List.of("JwtPropertiesTest", "OrderServiceIT", "PriceCalculatorTests", "ShopliteApiSmokeIT", "OrderChecks", "CartSpec", "TestDataBuilder"); for (String name : classes) { System.out.printf("%-22s %s%n", name, pluginFor(name)); } }}JwtPropertiesTest Surefire (mvn test) OrderServiceIT Failsafe (mvn verify) PriceCalculatorTests Surefire (mvn test) ShopliteApiSmokeIT Failsafe (mvn verify) OrderChecks nobody - never run CartSpec nobody - never run TestDataBuilder Surefire (mvn test)
What this code does
- Surefire's defaults are
Test*,*Test,*Testsand*TestCase; Failsafe's areIT*,*ITand*ITCase. A class calledOrderChecksorCartSpeccompiles fine and is silently never run. TestDataBuilderis a helper with no@Testmethods, but its name starts withTest, so Surefire looks at it and finds nothing to run. Name helpers likeOrderTestDataorProductBuilderto avoid confusion.
Surefire runs the *Test classes and Failsafe runs the *IT classes such as OrderServiceIT. So mvn test gives fast feedback and mvn verify runs everything.
-DskipTests compiles the tests but runs none of them, and -Dmaven.test.skip=true does not even compile them. Use them only for a real emergency, such as a hot-fix build while the test database is down, and never to hide a red test: a skipped test protects nobody.
Order of execution
What mvn verify runs
Put the steps of mvn verify in the order Maven runs them.
Next step
Check your understanding
10 quick questions