Maven Lifecycle

 

The Maven Build Lifecycle is a sequence of phases that define the order in which the goals (tasks) are executed to build and manage a project. Maven follows a well-defined standard lifecycle, which simplifies the build process and provides consistency across different projects.


What is a Build Lifecycle?

build lifecycle is essentially a well-defined sequence of phases that need to be executed to build a project. Each phase represents a stage in the lifecycle.

Maven has three built-in lifecycles:

  1. default – handles your project deployment (most commonly used).

  2. clean – handles project cleaning (deletes old builds).

  3. site – handles the creation of your project’s documentation.



1. Default Lifecycle (Core Build Lifecycle)

This is the main lifecycle and consists of 23 phases, out of which the most commonly used ones are:


PhaseDescription
validateValidates the project is correct and all necessary information is available.
initializeInitializes build state, sets properties.
generate-sourcesGenerates any source code needed before compilation.
process-sourcesProcesses the source code, like filtering.
generate-resourcesGenerates resources for inclusion in the package.
process-resourcesCopies and processes resources (like properties files) to the output directory.
compileCompiles the source code.
process-classesPost-processes the compiled classes (e.g., bytecode enhancement).
generate-test-sourcesGenerates test source code.
process-test-sourcesProcesses the test source code.
test-compileCompiles test source code.
process-test-classesPost-processes compiled test classes.
testRuns tests using a suitable unit testing framework.
prepare-packagePerforms operations before packaging like war/jar customization.
packagePackages the compiled code into a JAR/WAR.
pre-integration-testSetup steps before running integration tests.
integration-testRuns integration tests.
post-integration-testCleanup after integration tests.
verifyRuns checks to ensure the quality and correctness of the package.
installInstalls the package into the local Maven repository.
deployCopies the final package to the remote repository.



2. Clean Lifecycle

Used to clean the project before building. It has 3 phases:


PhaseDescription
pre-cleanExecuted before the actual project cleaning.
cleanDeletes the target/ directory (build output).
post-cleanExecuted after the cleaning is complete.




3. Site Lifecycle

Used to generate documentation for the project. It has 4 phases:


PhaseDescription
pre-siteExecuted before generating the site.
siteGenerates the project documentation.
post-siteExecutes operations needed after the site is generated.
site-deployDeploys the site to a web server.


Example Command Execution

mvn clean install

Above command will:

  • clean: delete the old target/ directory.
  • install: run the full default lifecycle (validate → compile → test → package → install).

Maven Project Structure

 

What is a Maven Project?

Maven project is a structured Java-based software project that uses Apache Maven as its build automation and dependency management tool. It is defined using a file called pom.xml (Project Object Model), which describes the project, its dependencies, build plugins, goals, and other configuration.


Standard Maven Project Folder Structure

Here's the default Maven directory structure (used in most Java projects):

project-root/

├── pom.xml                 # Main configuration file (Project Object Model)
├── src/
   ├── main/
      ├── java/           # Application/Source code
      ├── resources/      # Configuration files, properties files, XMLs
   ├── test/
      ├── java/           # Unit and integration test code
      ├── resources/      # Resources needed for testing

├── target/                 # Output directory for compiled classes and built artifacts (e.g., .jar/.war)
└── .mvn/                   # Maven wrapper files (optional)



Description of Important Folders and Files


Folder/FileDescription
pom.xmlCore file. Contains project info, dependencies, plugins, build configurations, etc.
src/main/java/Java source code for the application.
src/main/resources/Non-code resources like application.properties, log configs, XMLs.
src/test/java/Java unit or integration test source code.
src/test/resources/Resource files used for testing (e.g., test configs or mock data).
target/Auto-generated folder. Stores compiled classes, JAR/WAR files, and reports.
.mvn/Optional folder for Maven wrapper support (mvnw, mvnw.cmd, .mvn/wrapper).


Build Lifecycle Overview

When you run a Maven build (mvn clean install), Maven:

  • Compiles your source code
  • Runs tests in src/test/java
  • Packages the code into a .jar or .war file
  • Installs it into your local Maven repository

pom.xml


<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 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- Example dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Environment Setup for Maven

 

Setting up the Maven environment is a crucial step for managing Java-based projects efficiently. Below is a detailed step-by-step guide to install and set up Apache Maven on WindowsLinux, and macOS.


1. Prerequisites for All OS

Before you install Maven:

  • Java (JDK) must be installed.

  • Ensure the JAVA_HOME environment variable is set.

How to Check java installed on machine:


java -version
javac -version


If not installed, download Java JDK from: https://www.oracle.com/java/technologies/javase-downloads.html or use OpenJDK (https://jdk.java.net/)


Windows Installation Steps

Step 1: Download Maven


Step 2: Extract and Place Maven

  • Extract it to a folder (example: C:\Program Files\Apache\Maven)


Step 3: Set Environment Variables

  1. Search for “Environment Variables” in Start Menu.

  2. Under System Variables:

    • Add MAVEN_HOME:

Variable Name: MAVEN_HOME
Variable Value: C:\Program Files\Apache\Maven\apache-maven-3.9.6

Edit the Path variable and add:

%MAVEN_HOME%\bin


Ensure JAVA_HOME is set:

If not, add:


Variable Name: JAVA_HOME
Variable Value: path to JDK (e.g., C:\Program Files\Java\jdk-17)

Step 4: Verify Installation


mvn -v


Linux Installation Steps:

Step 1: Install Java


sudo apt update
sudo apt install openjdk-17-jdk


Set JAVA_HOME:


echo "export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which javac))))" >> ~/.bashrc
source ~/.bashrc


Step 2: Download Maven


wget https://downloads.apache.org/maven/maven-3/3.9.6/binaries/apache-maven-3.9.6-bin.tar.gz


Step 3: Extract and Move


tar -xvzf apache-maven-3.9.6-bin.tar.gz
sudo mv apache-maven-3.9.6 /opt/maven


Step 4: Set Environment Variables
Edit ~/.bashrc or ~/.zshrc:



export MAVEN_HOME=/opt/maven
export PATH=$MAVEN_HOME/bin:$PATH

Apply changes:


source ~/.bashrc


Step 5: Verify Installation


mvn -v


macOS Installation Steps

Option 1: Using Homebrew (Recommended)



brew install maven


Option 2: Manual Installation

Step 1: Install Java

Use brew install openjdk or download from Oracle.

Step 2: Download Maven

Download from https://maven.apache.org/download.cgi

Step 3: Extract and Move

tar -xvzf apache-maven-3.9.6-bin.tar.gz
sudo mv apache-maven-3.9.6 /opt/maven

Step 4: Set Environment Variables

Edit your shell profile (~/.zshrc~/.bash_profile, or ~/.bashrc):


export JAVA_HOME=$(/usr/libexec/java_home)
export MAVEN_HOME=/opt/maven
export PATH=$MAVEN_HOME/bin:$PATH


Apply changes:


source ~/.zshrc  # or relevant shell file


Step 5: Verify


mvn -v


Output:


Apache Maven 3.9.6
Java version: 17.0.1
Java home: C:\Program Files\Java\jdk-17
Default locale: en_US
OS name: "windows 10", version: "10.0", arch: "amd64"

Introduction to Apache Maven

  

What is Maven?

Maven is a build automation and project management tool primarily used for Java projects, although it can be used for other programming languages as well. It was developed by the Apache Software Foundation.


Why Maven?

Before Maven, Java developers used tools like Ant or wrote custom scripts to manage builds. However, these methods had drawbacks:

  • Complex and inconsistent project structures

  • Manual handling of dependencies

  • Difficulties in project configuration sharing


Maven solves these issues by offering a standardized and automated way to manage:

  • Project builds

  • Dependencies

  • Documentation

  • Testing

  • Deployment


Core Concepts of Maven

1. Project Object Model (POM)

  • The heart of a Maven project.

  • A file named pom.xml that contains:

    • Project details (name, version, etc.)

    • Dependencies

    • Plugins

    • Build configuration

    • Repository information

  • It acts as a blueprint of the project.


2. Convention over Configuration

  • Maven uses standard conventions to reduce the need for configuration.

  • Default folder structure:

src/
  main/java      source code
  main/resources  configuration files
  test/java       unit test code
  • You can override defaults, but following the convention simplifies project setup.


3. Dependency Management

  • Maven can automatically download and manage external libraries (dependencies).

  • It uses Maven Central Repository by default, but other repositories can be added.

  • Transitive dependency resolution: if library A depends on B, and B depends on C, Maven includes all of them automatically.



4. Build Lifecycle

  • Maven defines a set of phases for building a project:


PhaseDescription
validateChecks project structure
compileCompiles source code
testRuns unit tests
packagePackages compiled code (example: JAR or WAR)
verifyRuns checks (like integration tests)
installInstalls the package to local repository
deployDeploys the package to remote repository


5. Repositories

  • Local Repository: Stored on your system. Maven downloads dependencies here.

  • Central Repository: Official online repository (https://search.maven.org).

  • Remote Repository: Custom or enterprise-level repositories like Nexus or Artifactory.


6. Plugins

  • Provide additional functionality like:

    • Compiling code

    • Running tests

    • Creating documentation

    • Deploying applications



Advantages of Using Maven

  • Standardization: Enforces consistent project structures and builds.

  • Automation: Handles the full build lifecycle from compilation to deployment.

  • Dependency Management: Automatically downloads and updates libraries.

  • Portability: Same build works across machines/environments.

  • Integration: Works with IDEs like IntelliJ, Eclipse, and build servers like Jenkins.




Maven can be used for:

  • Building Java applications (JAR, WAR, EAR)
  • Managing complex dependency trees
  • Automating tests and deployment pipelines
  • Sharing libraries across teams or organizations

Integration of Karate API with JUnit 4

  

Integrating JUnit 4 with Karate API

Karate is a powerful testing framework based on BDD (Behavior Driven Development), especially useful for testing web services and APIs. It uses Gherkin syntax (like Cucumber) and can be integrated with JUnit 4 for test execution.


Step-by-Step Integration of Karate with JUnit 4


Step 1: Add Dependencies


<dependencies>
    <!-- Karate Core -->
    <dependency>
        <groupId>com.intuit.karate</groupId>
        <artifactId>karate-junit4</artifactId>
        <version>1.4.1</version> <!-- or latest stable version -->
        <scope>test</scope>
    </dependency>

    <!-- For Assertions and Test Reporting -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>




Step 2: Create Feature File

Create a file named sample.feature under:


src/test/java/examples




Feature file:

Feature: Sample API Test

  Scenario: Verify GET request
    Given url 'https://jsonplaceholder.typicode.com/posts/1'
    When method get
    Then status 200
    And match response.userId == 1


Step 3: Create JUnit 4 Test Runner

Create a Java class to run the above feature with JUnit 4.

src/test/java/examples/SampleRunnerTest.java:


package examples;

import com.intuit.karate.junit4.Karate;
import org.junit.runner.RunWith;

@RunWith(Karate.class)
public class SampleRunnerTest {
    // No need to write any code inside
}

This class tells JUnit 4 to use Karate as the test runner and will automatically find the .feature file in the same package.


Step 4: Run the Test

  • Right-click on SampleRunnerTest.java and choose Run As → JUnit Test

  • Or run via Maven:


mvn test



Step 5: View Reports

Karate automatically generates reports in target/karate-reports:

  • karate-summary.html

  • karate.log

  • karate-report.html




Optional: Run All Feature Files in a Folder

package examples;

import com.intuit.karate.junit4.Karate;
import org.junit.runner.RunWith;

@RunWith(Karate.class)
public class AllTests {
    // This will run all *.feature files in this package
}




Benefits of Karate + JUnit 4 Integration


FeatureDescription
BDD SyntaxSimple, readable Gherkin language
JUnit CompatibilityEasily integrates into CI/CD
Rich ReportingAuto HTML & JSON reports
No Java Code NeededScenarios are defined in .feature files

Test Runner in Cucumber using JUnit

  

To implement a Test Runner class with JUnit in Cucumber, you need to create a class annotated with @RunWith and @CucumberOptions. This class serves as the entry point for running your Cucumber test scenarios written in .feature files using JUnit.


Below are the steps to implement Test runner in Cucumber with Testng


1. Add Maven Dependencies

Make sure your pom.xml contains these dependencies:

<dependencies>
    <!-- Cucumber JUnit -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>7.11.1</version>
        <scope>test</scope>
    </dependency>

    <!-- JUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

    <!-- Cucumber Java -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.11.1</version>
    </dependency>
</dependencies>


 

2. Create Feature File

Example: src/test/resources/features/login.feature

Feature: Login functionality

  Scenario: Valid login
    Given user is on login page
    When user enters valid username and password
    Then user is navigated to the homepage



3. Create Step Definition File

Example: src/test/java/stepdefinitions/LoginSteps.java

package stepdefinitions;

import io.cucumber.java.en.*;

public class LoginSteps {

    @Given("user is on login page")
    public void user_is_on_login_page() {
        System.out.println("User is on login page");
    }

    @When("user enters valid username and password")
    public void user_enters_valid_username_and_password() {
        System.out.println("User enters credentials");
    }

    @Then("user is navigated to the homepage")
    public void user_is_navigated_to_the_homepage() {
        System.out.println("User navigated to homepage");
    }
}



4. Create Test Runner Class

Example: src/test/java/testrunner/TestRunner.java

package testrunner;

import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)  // Tells JUnit to run Cucumber tests
@CucumberOptions(
    features = "src/test/resources/features", // path to feature files
    glue = "stepdefinitions",                // package of step definitions
    plugin = {"pretty", "html:target/cucumber-reports.html"},
    monochrome = true
)
public class TestRunner {
    // No code needed here
}



5. Run the Test

You can run the TestRunner.java file like a normal JUnit test class. Cucumber will pick the .feature files and corresponding step definitions.



Important Points:

ComponentDescription
@RunWith(Cucumber.class)Instructs JUnit to use Cucumber's test runner
@CucumberOptionsProvides feature path, glue (steps), plugin, formatting
featuresPath to .feature files
gluePackage containing step definition files
pluginReporting output (HTML, JSON, etc.)
monochromeMakes console output more readable