Answer
Running Selenium + TestNG Tests in Jenkins
Project Prerequisites
XML
<!-- pom.xml — key dependencies -->
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
<!-- Pass Jenkins params to tests -->
<systemPropertyVariables>
<browser>${browser}</browser>
<env>${env}</env>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
Jenkins Declarative Pipeline
GROOVY
pipeline {
agent any
parameters {
choice(name: 'BROWSER', choices: ['chrome', 'firefox', 'edge'], description: 'Browser to run tests')
choice(name: 'ENV', choices: ['staging', 'qa', 'prod'], description: 'Target environment')
string(name: 'SUITE', defaultValue: 'testng.xml', description: 'TestNG suite file')
}
tools {
maven 'Maven-3.9'
jdk 'JDK-17'
}
stages {
stage('Checkout') {
steps {
git branch: 'main',
credentialsId: 'github-creds',
url: 'https://github.com/org/selenium-framework.git'
}
}
stage('Build') {
steps {
sh 'mvn clean compile -q'
}
}
stage('Run Tests') {
steps {
sh """
mvn test \
-Dbrowser=${params.BROWSER} \
-Denv=${params.ENV} \
-Dsurefire.suiteXmlFiles=${params.SUITE}
"""
}
}
}
post {
always {
// Publish JUnit results (shows pass/fail graph in Jenkins)
junit testResults: 'target/surefire-reports/*.xml',
allowEmptyResults: true
// Publish Allure Report (requires Allure plugin)
allure([
includeProperties: false,
jdk: '',
properties: [],
reportBuildPolicy: 'ALWAYS',
results: [[path: 'target/allure-results']],
])
// Or publish Extent Report HTML
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'target/extent-reports',
reportFiles: 'index.html',
reportName: 'Extent Test Report',
reportTitles: '',
])
}
failure {
emailext(
subject: "TESTS FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: "Build URL: ${env.BUILD_URL}\nBrowser: ${params.BROWSER}",
to: 'qa-team@company.com'
)
}
always {
cleanWs() // clean up workspace
}
}
}
Headless Chrome on Jenkins (Linux Agent)
GROOVY
stage('Run Tests') {
steps {
// Chrome options for headless in CI
sh 'mvn test -Dbrowser=chrome-headless'
}
}
Java
// In your DriverManager.java
if ("chrome-headless".equals(browser)) {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
options.addArguments("--no-sandbox"); // required for CI
options.addArguments("--disable-dev-shm-usage"); // required for CI
options.addArguments("--window-size=1920,1080");
return new ChromeDriver(options);
}
