Maven doesn't just "run tests." It follows a strict lifecycle — a sequence of phases that run in order. When you say mvn test, Maven first validates the project, compiles the main code, compiles the test code, THEN runs the tests. You can't skip steps.
The critical rule: when you run a phase, all earlier phases run first. So mvn test actually runs: validate → compile → test-compile → test. And mvn package runs everything up to and including package.
There's a separate clean lifecycle with one important phase: clean. It deletes the entire target/ directory — removing compiled code, old test reports, and stale artifacts. This is why you should always run mvn clean test, not just mvn test.
If you run mvn test without clean, Maven might use old compiled .class files from a previous build. This leads to bizarre bugs: "I changed my code but tests still behave the same." Always run mvn clean test to start fresh. In CI/CD, this is mandatory.
| Phase | What It Does | How Often You Use It |
|---|---|---|
| clean | Deletes target/ directory | Every time — always start fresh |
| compile | Compiles src/main/java | Runs automatically as part of test |
| test-compile | Compiles src/test/java | Runs automatically as part of test |
| test | Runs your TestNG/JUnit tests | Your most-used phase — daily |
| package | Creates a JAR file | Rarely needed for QA projects |
| install | Puts JAR in local repo | Only if other projects import your framework |
Q: What is the Maven build lifecycle? Which phases do you use?
A: Maven build lifecycle is a sequence of phases that run in order: validate, compile, test-compile, test, package, verify, install, deploy. When you run a specific phase, all earlier phases execute first. As a QA automation engineer, I primarily use two commands: mvn clean test for running tests (clean deletes old builds, then test runs validate through test), and mvn clean test -DsuiteXmlFile=smoke.xml for running specific suites. The key thing is that mvn test automatically compiles code before running tests — you don't need to compile separately.
Q: What is the difference between mvn test and mvn clean test?
A: mvn test runs phases from validate through test, but it may reuse previously compiled class files from the target/ directory. mvn clean test first deletes the target/ directory (removing all old compiled files and reports), then runs the full lifecycle. Always use mvn clean test in CI pipelines to ensure a fresh build without stale artifacts from previous runs.
In interviews, they love asking "what happens when you run mvn test?" The expected answer: Maven runs validate → compile → test-compile → test. It does NOT run package, install, or deploy. Show that you understand the lifecycle is sequential and each phase includes all prior phases.
Key Point: Maven lifecycle phases run in order. mvn test = validate + compile + test-compile + test. Always use mvn clean test to start fresh.