How to Build and Test in Maven?
Maven is a build automation and dependency management tool used primarily for Java projects. It uses a file called pom.xml (Project Object Model) to manage builds, dependencies, plugins, and more.
1. Building a Maven Project
Steps to Build:
Step 1: Install Maven
Download Maven from https://maven.apache.org/download.cgi
Set environment variables:
MAVEN_HOME→ path to Maven folderAdd
%MAVEN_HOME%\bintoPATH- Check with:
mvn -version
Step 2: Navigate to Project Directory
cd path/to/your/project
Step 3: Run Build Commands
Common Maven Build Commands:
Common Maven Build Commands:
| Command | Description |
|---|---|
| mvn validate | Validate project structure and configuration |
| mvn compile | Compile the Java source code |
| mvn test | Run unit tests using JUnit/TestNG |
| mvn package | Compile + bundle code into a JAR/WAR file |
| mvn install | Install package to local .m2 repository |
| mvn clean | Delete the target/ folder (cleans old builds) |
| mvn clean install | Clean → compile → test → package → install |
2. Testing in Maven
Maven runs tests using Surefire Plugin, and the test classes must follow these conventions:
Write a Unit Test
Example with JUnit:
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CalculatorTest { @Test public void testAddition() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } }
Run Tests
mvn test
Skip Tests
mvn install -DskipTests
Run Specific Test
mvn -Dtest=CalculatorTest test
Plugins That Help Build & Test
| Plugin | Purpose |
|---|---|
| maven-compiler-plugin | Compiles Java code |
| maven-surefire-plugin | Runs unit tests |
| maven-failsafe-plugin | Runs integration tests |
| maven-jar-plugin | Packages into .jar |
| maven-war-plugin | Packages into .war (for web apps) |
Example:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> </plugins> </build>