How to Build and Test in Maven

 


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

mvn -version



Step 2: Navigate to Project Directory


cd path/to/your/project




Step 3: Run Build Commands

Common Maven Build Commands:



CommandDescription
mvn validateValidate project structure and configuration
mvn compileCompile the Java source code
mvn testRun unit tests using JUnit/TestNG
mvn packageCompile + bundle code into a JAR/WAR file
mvn installInstall package to local .m2 repository
mvn cleanDelete the target/ folder (cleans old builds)
mvn clean installClean → 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


PluginPurpose
maven-compiler-pluginCompiles Java code
maven-surefire-pluginRuns unit tests
maven-failsafe-pluginRuns integration tests
maven-jar-pluginPackages into .jar
maven-war-pluginPackages 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>

No comments:

Post a Comment