</>

Technology

Jenkins

Difficulty

Intermediate

Interview Question

How do you set up a complete CI/CD pipeline in Jenkins for a Selenium Java project?

Answer

Complete Jenkins CI/CD Pipeline for Selenium Java

Step 1: Project Structure

CODE
selenium-framework/
├── src/
│   ├── main/java/com/automateqa/
│   │   ├── pages/
│   │   ├── utils/
│   │   └── config/
│   └── test/java/com/automateqa/
│       └── tests/
├── testng.xml
├── smoke-testng.xml
├── pom.xml
└── Jenkinsfile            ← pipeline definition

Step 2: pom.xml — Maven Surefire Configuration

XML
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.5</version>
    <configuration>
        <suiteXmlFiles>
            <suiteXmlFile>${suite}</suiteXmlFile>
        </suiteXmlFiles>
        <systemPropertyVariables>
            <browser>${browser}</browser>
            <env>${env}</env>
            <baseUrl>${baseUrl}</baseUrl>
        </systemPropertyVariables>
    </configuration>
</plugin>

Step 3: Jenkinsfile — Complete Pipeline

GROOVY
pipeline {
    agent any

    parameters {
        choice(name: 'BROWSER',
               choices: ['chrome', 'firefox', 'edge'],
               description: 'Browser to use for tests')
        choice(name: 'ENV',
               choices: ['staging', 'qa', 'prod'],
               description: 'Target environment')
        choice(name: 'SUITE',
               choices: ['testng.xml', 'smoke-testng.xml', 'regression-testng.xml'],
               description: 'TestNG suite to run')
    }

    tools {
        maven 'Maven-3.9'
        jdk   'JDK-17'
    }

    options {
        timeout(time: 90, unit: 'MINUTES')
        timestamps()
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }

    environment {
        BASE_URL = credentials("base-url-${params.ENV}")
    }

    stages {
        stage('Checkout') {
            steps {
                git branch: env.BRANCH_NAME ?: 'main',
                    credentialsId: 'github-creds',
                    url: 'https://github.com/org/selenium-framework.git'
                echo "Building branch: ${env.BRANCH_NAME}"
            }
        }

        stage('Build') {
            steps {
                sh 'mvn clean compile -q'
            }
        }

        stage('Run Tests') {
            steps {
                sh """
                    mvn test \
                      -Dbrowser=${params.BROWSER} \
                      -Denv=${params.ENV} \
                      -DbaseUrl=${BASE_URL} \
                      -Dsuite=${params.SUITE}
                """
            }
        }
    }

    post {
        always {
            // JUnit results — shows trends graph
            junit testResults: 'target/surefire-reports/*.xml',
                  allowEmptyResults: true

            // Allure Report
            allure([
                reportBuildPolicy: 'ALWAYS',
                results: [[path: 'target/allure-results']],
            ])

            // Cleanup workspace
            cleanWs()
        }

        failure {
            emailext(
                subject: "TESTS FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER} [${params.BROWSER}/${params.ENV}]",
                body:    """
                    <h2>Build Failed</h2>
                    <p><b>Job:</b>     ${env.JOB_NAME}</p>
                    <p><b>Build:</b>   #${env.BUILD_NUMBER}</p>
                    <p><b>Browser:</b> ${params.BROWSER}</p>
                    <p><b>Env:</b>     ${params.ENV}</p>
                    <p><b>URL:</b>     <a href="${env.BUILD_URL}">${env.BUILD_URL}</a></p>
                """,
                to:       'qa-team@company.com',
                mimeType: 'text/html',
            )
        }

        success {
            echo "All tests passed! Browser: ${params.BROWSER} | Env: ${params.ENV}"
        }
    }
}

Step 4: Headless Chrome Driver Setup (for Jenkins Linux)

Java
public static WebDriver createChromeDriver() {
    ChromeOptions options = new ChromeOptions();
    if (System.getProperty("browser", "chrome").equals("chrome")
            && Boolean.parseBoolean(System.getenv().getOrDefault("CI", "false"))) {
        options.addArguments("--headless=new");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--window-size=1920,1080");
    }
    return new ChromeDriver(options);
}

Follow AutomateQA

Related Topics