Jenkins

How Run Selenium Tests in Jenkins Using Maven

Jenkins is the leading open-source continuous integration tool developed by Hudson lab. It is cross-platform and can be used on Windows, Linux, Mac OS and Solaris environments. Jenkins is written in Java.it has taken the place as one of the best open-source tools that allow continuous integration and build management.

A quick summary of this blog post is listed below:

  • An overview of the tools chosen for setting up the framework: MavenJUnitSelenium and Jenkins, and how they interact.
  • Adding all the dependencies and plugins needed for the tools to a Java project
  • Creating a Selenium test.
  • Integrating the created test into a continuous ecosystem using Jenkins.

Why Jenkins and Selenium?

  • Running Selenium tests in Jenkins allows you to run your tests every time your software changes and deploy the software to a new environment when the tests pass.
  • Jenkins can schedule your tests to run at specific time.
  • You can save the execution history and Test Reports.
  • Jenkins supports Maven for building and Testing a project in continuous integration

What is Maven?

Maven is a powerful project / build management tool, based on the concept of a POM (Project Object Model) that includes project information and configuration information for Maven such as construction directory, source directory, dependency, test source directory, Goals, plugins, etc.

Why Maven & Selenium

Integrating Maven with Selenium provides following benefits Apache Maven provides support for managing the full lifecycle of a test project.

  • Maven is used to define project structure, dependencies, build, and test management.
  • Using pom.xml(Maven) you can configure dependencies needed for building testing and running code.
  • Maven automatically downloads the necessary files from the repository while building the project.

Tools Overview

The tools I’m using (in addition to Jenkins) are very popular and well-established for a Java ecosystem:

  • Maven: A Java software project management tool
  • JUnit: A Java unit testing library
  • Selenium WebDriver: A library that is used to automate browser interaction

Here is how the tools interact:

jenkins, selenium, maven and junit together
  • As you can see, when a Jenkins build is triggered, Maven downloads the latest code changes and updates, packages them and performs the build.
  • One of the build goals is to run the automated tests and that will take place through the maven-surefire-plugin.
  • The plugins tell JUnit to run all the tests in the project that have the annotation @Test.
  • Once a test is found, the Selenium Webdriver comes into play, opens a new browser instance and runs the automated user interface test.
  • At the end of the build, a default report is generated by Jenkins with the results of the tests.
  • If there is at least one failed test, the build is marked as failed.

We’ll assume Jenkins, Maven and Selenium Server are already installed (preferably on the same machine, for increased speed, but not mandatory). If you need help in installing any of the tools, check the links below, which will help, independent of the OS installed on your machine.

Creating a maven selenium script

1.In Eclipse IDE, create a new project by selecting File | New | Maven Project from Eclipse menu.

2.On the New Maven Project dialog select the Create a simple project and click Next.

3.Enter SeleniumScript in Group Id: and Artifact Id: and click finish.

4. Eclipse will create WebdriverTest with following structure:

5. Right-click on JRE System Library and select the Properties option from the menu.

6. On the Properties for JRE System Library dialog box, make sure Workspace default JRE is selected and click OK.

7. Select pom.xml from Project Explorer.

8.Add the Selenium, Maven, TestNG, Junit dependencies to pom.xml in the node:

<dependencies>			
        <dependency>				
             <groupId>junit</groupId>								
             <artifactId>junit</artifactId>								
             <version>3.8.1</version>								
             <scope>test</scope>								
        </dependency>				
        <dependency>				
            <groupId>org.seleniumhq.selenium</groupId>								
            <artifactId>selenium-java</artifactId>								
            <version>2.45.0</version>								
		</dependency>				
        <dependency>				
            <groupId>org.testng</groupId>								
            <artifactId>testng</artifactId>								
            <version>6.8</version>								
            <scope>test</scope>							  			
       </dependency>				
</dependencies>

9. Create a New TestNG Class File | New | Others | TestNG | TestNG class. Enter Package name as “Qautomation” and “TestScript” in the Name: textbox and click on the Finish button as shown in the following screenshot:

10. Eclipse will create the TestScript class 

11 Add the following code to the TestScript class and respective browser drivers for Chrome ,Firefox and IE:

package qautomation;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterTest;

public class TestScript {

	public static WebDriver driver=null;
	public String browser = System.getProperty("browser");
	public String url = System.getProperty("URL");
	
 @BeforeTest
  public void beforeTest() {
	
	if(browser.equalsIgnoreCase("Chrome"))
	{
	System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\chromedriver.exe");
	Map<String, Object> prefs = new HashMap<String, Object>();
	ChromeOptions options = new ChromeOptions();
	options.setExperimentalOption("prefs", prefs);
	options.addArguments("--disable-arguments");
	options.addArguments("--test-type");
	options.addArguments("test");	
	options.addArguments("disable-infobars");
	driver = new ChromeDriver(options);
	}
	else if(browser.equalsIgnoreCase("FireFox"))
	{
		System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
		System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,System.getProperty("user.dir")+"\\FireFoxLogs.txt");
		System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"\\geckodriver_v23.exe");
		FirefoxProfile profile = new FirefoxProfile();	    
		profile.setAcceptUntrustedCertificates(false);
	    FirefoxOptions options = new FirefoxOptions().setProfile(profile);
	    driver = new FirefoxDriver(options);
		driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
	    driver.manage().window().maximize();
	}
	else if (browser.equalsIgnoreCase("IE"))
	{
		System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\IEDriverServer351.exe");
		DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
		caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
		caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING,true);
		caps.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,"accept");
		caps.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS,true);
		caps.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,"http://www.google.com/");							
		driver = new InternetExplorerDriver(caps);	
		driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
	    driver.manage().window().maximize();
	}
	driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
	driver.manage().window().maximize();
  }

  @Test
  public void TestApplication() {
	  
	driver.get(url);  
	String title = driver.getTitle();	
	System.out.println("Title="+title);
	Assert.assertTrue(title.contains("QAutomation")); 
	
  }
 
  @AfterTest
  public void afterTest() {
	  driver.quit();		
  }

}

12. Right-click on the WebdriverTest and select TestNG | Convert to TestNG. Eclipse will create testng.xml which says that you need to run only one test with the name TestApplication as shown in the following screenshot:

13.Adding Dependencies and Plugins:

Additionally, we need to add

  1. maven-compiler-plugin
  2. maven-surefire-plugin
  3. testng.xml

to maven pom.xml.

The maven-surefire-plugin is used to configure and execute tests. Here plugin is used to configure the testing.xml for TestNG test and generate test reports.

The maven-compiler-plugin is used to help in compiling the code and using the particular JDK version for compilation. Add all dependencies in the following code snippet, to pom.xml in the <plugin> node:

<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<sourceDirectory>src/main/java</sourceDirectory>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>2.3.2</version>
					<configuration>
						<encoding>iso-8859-1</encoding>
						<source>1.8</source>
						<target>1.8</target>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-surefire-plugin</artifactId>
					<version>2.19.1</version>
					<configuration>
						<suiteXmlFiles>
							<suiteXmlFile>${suiteXmlFiles}</suiteXmlFile>
						</suiteXmlFiles>
						<!--reportsDirectory>${project.basedir}/Reports/TestReport_${timestamp}</reportsDirectory>-->
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

Integrating Your Test Into Jenkins

Assuming you have already a running Jenkins application.

  1. Launch and login into Jenkins URL – http://localhost:8080/

2.Click on New Item and Enter an appropriate name for the new Job, select Maven Project project and click on Save.

3. A new, empty job has been created at this point

4.Jenkins Parameterized Build :To make a parameterized build in Jenkins just check the checkbox This project is parameterized and add the parameter by Add Parameter as per your project requirement.

5.If your code is located on Git Under Source Management, select the appropriate repository for the location of your project and pass the URL and credentials.

if a versioning system is used in a project, there will be a structure of a main branch called master and various other branches. In Jenkins, you need to specify which branch of the project should be used, or leave blank if there is no versioning system used or it has only the main one (master).

functional testing in jenkins automation

6.In the “Pre-steps” build section, another set of parameters can be passed to the Jenkins build. Here you will specify the Maven targets that need to be executed in order to run your test, in this case “clean test” and parameters you passed for browsers , URLand credentials etc.

if your source code is located on Git the do below setting under Build section:

If you have selenium code on your local just pass the pom.xml path in Root POM .

7. Last but not least, in the configuration of a new build, Jenkins allows the possibility of notifying specified users regarding the results of a build via e-mail or the feature of archiving different artifacts generated at the end of a build. In our case it could be test results saved in an excel file, other types of test reports, screenshots taken during the execution of the tests and so on.

8. Run the test in Jenkins by clicking on Build with Parameters .

9. Select the browser you wanna run from dropdown.

10. Select the TestSuit file

11. Click the Build Button and go to Console Output.

12. You can see the logs from Console Output window.

Note : Blue color of ball of console output is that build is successful.

You can view the HTML Report just click on the Link

Click Test Analyzer to analyse the result

References:

https://jenkins.io/doc/tutorials/build-a-java-app-with-maven/

https://wiki.jenkins.io/display/JENKINS/Selenium+Plugin

https://www.seleniumeasy.com/jenkins-tutorials

https://www.blazemeter.com/blog/how-to-setup-and-run-selenium-tests-in-jenkins-using-maven-and-junit

Categories: Jenkins, Selenium

1 reply »

Leave a Reply