Knowing which goals run in which phase explains why tests run on package and how to hook in extra steps.
Maven has three built-in lifecycles: default (build), clean and site. A lifecycle is an ordered list of phases. Running a phase runs it and every phase before it. The main phases of default:
1. validate 2. compile (compiles src/main/java) 3. test-compile, then test (runs unit tests with the Surefire plugin) 4. package (builds the jar/war with the Jar plugin) 5. integration-test and verify (Failsafe runs integration tests named *IT) 6. install (copies to ~/.m2) 7. deploy (uploads to a remote repository)
So mvn package compiles, runs tests and builds the jar; mvn install additionally installs it. mvn clean install first runs the clean lifecycle.
Phases do nothing themselves. Work is done by plugin goals such as compiler:compile, surefire:test or jar:jar, which the packaging type binds to phases by default. You can run a goal directly without the lifecycle: mvn dependency:tree, mvn versions:display-dependency-updates, mvn help:effective-pom (shows the POM after inheritance and defaults).
Bind extra goals to phases in <build><plugins> with an <executions> block, for example running a code generator in generate-sources or Failsafe in integration-test.
-DskipTests compiles tests but doesn't run them; -Dmaven.test.skip=true skips compiling them too.
Example
# Each phase runs all earlier phases
mvn compile # validate -> compile
mvn test # ... -> test-compile -> test (Surefire)
mvn package # ... -> package (Jar plugin)
mvn verify # ... -> integration-test -> verify (Failsafe)
mvn install # ... -> install (~/.m2/repository)
mvn clean install # clean lifecycle first, then default up to install
# Goals can be invoked directly, outside the lifecycle
mvn help:effective-pom # POM after inheritance and defaults
mvn dependency:tree
mvn surefire:test -Dtest=UserServiceTest
mvn versions:display-dependency-updates
# Skipping tests
mvn package -DskipTests # compile tests but don't run
mvn package -Dmaven.test.skip=true # don't even compile themRemember
- A phase runs every phase before it
- Plugins' goals are bound to phases; packaging sets the defaults
- verify includes Failsafe integration tests; install copies to ~/.m2
- plugin:goal runs a goal directly