How To Integrate Jenkins & Maven With Selenium?

Image for post
Image for post

Note: The code samples may be displayed improperly because of markdown. I recommend continuing to read the original article Maven and Jenkins with Selenium to make sure all the examples are displayed properly.

Overview Of Selenium, Maven, & Jenkins

Maven is a popular build automation tool that is primarily used for Java projects. The advantage of using Maven is that Java libraries and plugins are downloaded on a dynamic basis from the Maven 2 Central Repository.

  • TestNG — Popular test automation framework [Link]
  • Selenium WebDriver — Library primarily used for automation of browser interactions [Link]
  • Jenkins — Tool for Continuous Integration (CI) and Continuous Deployment (CD) [Link]
Image for post
Image for post
  • Maven downloads the dependent libraries & packages and starts performing the build. The information related to the test suite is available in testing.xml, and the same is also used in pom.xml.
  • A build goal (e.g., install) for running the automated tests is set. The same is achieved through the maven-surefire-plugin.
  • The maven-surefire-plugin tells TestNG to run the tests that are under the annotation @Test.
  • Depending on the AUT (application under test) and the browser (& OS combination) on which cross browser tests are performed, the Selenium WebDriver invokes the corresponding browser instance and executes the same automation tests.
  • Test results are published in HTML Reports, as the HTML Publisher plugin is used for report generation.
  • Even if a single test case has failed, the complete test is marked with status ‘Failed.’

Advantages Of Using Maven & Jenkins With Selenium

Before we demonstrate the usage of Selenium Maven Jenkins integration, we will take a look at the main advantages of using Maven and Jenkins with Selenium:

  • Test suites that comprise many test scenarios (or test combinations) might take a longer duration for automation testing. A nightly build run can be scheduled for build and execution on the Jenkins server in such cases.
  • As Maven uses pom.xml, it reduces the overall dependency of the manual download of jar files. Also, the ‘Maven Project’ type in Jenkins helps in getting started with Selenium Maven, Jenkins integration with a few configuration settings.
  • The Selenium Maven Jenkins integration setup is suited for developing and testing teams distributed across different geographical locations.

Prerequisites For Jenkins Selenium Project

For demonstration of Maven and Jenkins with Selenium, the following softwares should be installed (or available) on the machine from where tests are triggered:

Demonstrating Selenium Maven Jenkins Integration

For time-saving purposes, we would not look into every step of the creation of a Maven Project. In case you would like a quick recap of Maven with Selenium, you can refer to this Maven tutorial for Selenium test automation. The steps used for creating a Maven project in IntelliJ IDEA are similar to those used in creating a Maven project in Eclipse IDE.

Test Suite — 1

Test Scenario — 1 (Chrome on Windows 10)

  1. Choose the first two checkboxes.
  2. Enter ‘Happy Testing at LambdaTest’ in the textbox below with the following id = sampletodotext.
  3. Now, click on the Add Button and verify whether the text has been added or not.
  1. Search for “LambdaTest”.
  2. Click on the first test result.
  3. Now, raise an Assert if the Page Title does not match the expected title.

Implementation

The appropriate dependencies and plugins have to be added in the project’s pom.xml. Here are the key packages (or jars) that are a part of pom.xml:

  • TestNG framework (version 6.9.10)
  • Maven Surefire plugin for execution of test suite which is a part of testng.xml
  • Maven Surefire Report plugin for generating the test results report into an HTML format
Image for post
Image for post
Image for post
Image for post
<listeners>
<listener class-name=”org.selenium4.GoogleSearchTest”/>
</listeners>

<test name=”Google Search Test — 1">
<parameter name=”browser” value=”Chrome”/>
<parameter name=”version” value=”latest”/>
<parameter name=”platform” value=”Windows 10"/>
<parameter name=”resolution” value=”1600x1200"/>
<classes>
<class name=”org.selenium4.GoogleSearchTest”/>
</classes>
</test>

Code Walkthrough

Step 1 — The necessary packages are imported before the actual implementation kicks off. Since the TestNG framework is used for testing; hence, its packages are also imported before its annotations can be used.

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.junit.Assert.*;
import org.junit.Test.*;
public class GoogleSearchTest implements IExecutionListener {
/* protected static EdgeDriver driver; */
String URL = “https://www.google.com/";
…………………………..
…………………………..
…………………………..

@Override
public void onExecutionStart() {
System.out.println(“onExecutionStart”);
}

@Override
public void onExecutionFinish() {
System.out.println(“onExecutionFinish”);
}
public class GoogleSearchTest implements IExecutionListener {
/* protected static EdgeDriver driver; */
String URL = “https://www.google.com/";
String search_string = “LambdaTest”;
WebDriver driver = null;
…………………………
…………………………

public static String status = “passed”;
public static String username = “user-name”;
public static String access_key = “access-key”;
…………………………
…………………………

@BeforeTest
@Parameters(value={“browser”,”version”,”platform”, “resolution”})

public void testSetUp(String browser, String version, String platform, String resolution) throws Exception {
…………………………
…………………………
}
public void testSetUp(String browser, String version, String platform, String resolution) throws Exception {

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(“build”, “Google Search — Maven Parallel Testing with Jenkins Pipeline”);
capabilities.setCapability(“name”, “Google Search — Maven Parallel Testing with Jenkins Pipeline”);
…………………………
…………………………

try {
driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”), capabilities);
} catch (MalformedURLException e) {
System.out.println(“Invalid grid URL”);
}
System.out.println(“Started session”);
try {
driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”), capabilities);
}
catch (MalformedURLException e)
@Test
public void test_Selenium4_GoogleSearch() throws InterruptedException {
driver.navigate().to(URL);
driver.manage().window().maximize();

try {
/* Enter the search term in the Google Search Box */
search_box = driver.findElement(By.xpath(“//input[@name=’q’]”));
search_box.sendKeys(search_string);
search_box.submit();
……………………………………
……………………………………
}
……………………………………
……………………………………
}
WebElement lt_link = driver.findElement(By.xpath(“//h3[.=’LambdaTest: Most Powerful Cross Browser Testing Tool Online’]”));
lt_link.click();

/* Not a good programming practice, added for demonstration */
Thread.sleep(5000);
……………………………………
……………………………………
@AfterClass
public void tearDown() {
if (driver != null) {
((JavascriptExecutor) driver).executeScript(“lambda-status=” + status);
driver.quit();
}
}

Test Suite — 2

Test Scenario — 1 (Chrome on Windows 10)

  1. Check the Page Title
  2. Compare the Page Title with the expected title
  3. Assert if the titles do not match

Implementation

It is the same as the one which is used for Test Suite-1, except for the artifactId and groupID.

Image for post
Image for post

Setting Up Jenkins For The Jenkins Selenium Project

Before creating a new job in Jenkins that builds the project mentioned earlier, we have to set up the Jenkins environment.

Image for post
Image for post
java -Dhudson.model.DirectoryBrowserSupport.CSP=”sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; style-src ‘unsafe-inline’ *;” -Dsvnkit.http.sslProtocols=TLSv1 -jar Jenkins.war — httpPort=9090
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
JAVA_HOME — <Location where JDK is installed>
MAVEN_HOME — <Location where Maven is installed>
JAVA_HOME — C:\Program Files\Java\jdk1.8.0_251
MAVEN_HOME — C:\apache-maven\apache-maven-3.6.3\
Image for post
Image for post

Selenium Maven Jenkins Integration Using FreeStyle Project

For creating a FreeStyle project that uses Selenium Maven Jenkins integration as demonstration, perform the following steps on Jenkins UI (i.e. localhost:9090/)

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
mvn -T 4 clean install
Image for post
Image for post
Image for post
Image for post
HTML directory to archive — ${project_dir_1}/target/surefire-reports
Index Page(s) — index.html
Report Title — Test Scenario 1 Report
HTML directory to archive — ${project_dir_2}/target/surefire-reports
Index Page(s) — index.html
Report Title — Test Scenario 2 Report
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Report for Test Scenario — 1
Image for post
Image for post
Report for Test Scenario — 2

Selenium Maven Jenkins Integration Using Jenkins Pipeline

In this section of Maven and Jenkins with Selenium demonstration, we would be using the Jenkins Pipeline that uses Domain Specific Language (DSL) for realizing Pipeline as Code.

Image for post
Image for post
pipeline {
agent any
tools {
maven ‘MAVEN_3.6.3’
jdk ‘JDK_1.8.0_251’
}
stages {
stage(‘Run Tests’) {
environment {
PROJECT_DIR_1 = “C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins”
PROJECT_DIR_2 = “C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins_2”
}
parallel {
stage(‘Test Scenario 1’) {
agent {
label “Slave_1”
}
steps {
echo ‘maven clean’
bat ‘ mvn -f %PROJECT_DIR_1%\\pom.xml clean install’
}
post {
success {
publishHTML ([
allowMissing: false,
alwaysLinkToLastBuild: false,
includes: ‘**/*’,
keepAll: true,
reportDir: ‘C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins\\target\\surefire-reports’,
reportFiles: ‘index.html’,
reportName: ‘Test Scenario 1 Report’
])
}
}
}
stage(‘Test Scenario 2’) {
agent {
label “Slave_2”
}
steps {
echo ‘maven clean’
bat ‘ mvn -f %PROJECT_DIR_2%\\pom.xml clean install’
}
post {
success {
publishHTML ([
allowMissing: false,
alwaysLinkToLastBuild: false,
includes: ‘**/*’,
keepAll: true,
reportDir: ‘C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins_2\\target\\surefire-reports’,
reportFiles: ‘index.html’,
reportName: ‘Test Scenario 2 Report’
])
}
}
}
}
}
}
}
Image for post
Image for post

Pipeline Walkthrough

Step 1: This specific Jenkins job can run on any Agent. The section with the tools directive contains all the tools that have to be installed automatically. The same is then also added to the PATH environment variable.

pipeline {
agent any
tools {
maven ‘MAVEN_3.6.3’
jdk ‘JDK_1.8.0_251’
}
Image for post
Image for post
stages {
stage(‘Run Tests’) {
environment {
PROJECT_DIR_1 = “C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins”
PROJECT_DIR_2 = “C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins_2”
}
stages {
stage(‘Run Tests’) {
environment {
PROJECT_DIR_1 = “C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins”
PROJECT_DIR_2 = “C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins_2”
}
parallel {
stage(‘Test Scenario 1’) {
…………………………………..
…………………………………..
}
stage(‘Test Scenario 2’) {
…………………………………..
…………………………………..
}
}
}
}
parallel {
stage(‘Test Scenario 1’) {
agent {
label “Slave_1”
}
………….
………….
stage(‘Test Scenario 2’) {
agent {
label “Slave_2”
}
Image for post
Image for post
Image for post
Image for post
steps {
echo ‘maven clean’
bat ‘ mvn -f %PROJECT_DIR_1%\\pom.xml clean install’
}
post {
success {
publishHTML ([
allowMissing: false,
alwaysLinkToLastBuild: false,
includes: ‘**/*’,
keepAll: true,
reportDir: ‘C:\\Users\\Lenovo\\IdeaProjects\\Maven_Jenkins\\target\\surefire-reports’,
reportFiles: ‘index.html’,
reportName: ‘Test Scenario 1 Report’
])
}
}
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Wrapping up

Image for post
Image for post

Written by

Product Growth at @lambdatesting (www.lambdatest.com)