How to change chrome download path using selenium

How to change chrome download path using selenium
How to change chrome download path using selenium

We can change our chrome download folder location from chrome settings and provide our desired location, but in case of automation, we need to change our download location dynamically. Suppose we need to download a file from an application and need to verify the downloaded file is a valid file or not. We have different API or jars are available to verify the document. I will discuss this verification in my later post. First, we need to download the file in a folder and folder will be created in runtime may be based on timestamp. So you can understand download path will be different every run. 

There is the code which will set the chrome download path runtime. 


 public WebDriver driver;  
 System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");  
 HashMap<String, Object> chromePrefs = new HashMap<String, Object>();  
 chromePrefs.put("profile.default_content_settings.popups", 0);  
 chromePrefs.put("download.default_directory", downloadFilepath);  
 ChromeOptions options = new ChromeOptions();  
 options.setExperimentalOption("prefs", chromePrefs);  
 options.addArguments("--disable-notifications");  
 DesiredCapabilities cap = DesiredCapabilities.chrome();  
 cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);  
 cap.setCapability(ChromeOptions.CAPABILITY, options);  
 System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");  
 driver = new ChromeDriver(options);  

Hope it will solve your problem. 

What is the "Background" keyword in Cucumber feature file


What is the "Background" keyword in Cucumber feature file


When we are writing Feature file in cucumber,  we write multiple Scenarios. All scenarios start with a particular point. Suppose  I am writing the feature file called home_page_facebook and the number of scenarios is there to check the home page functionality. Now if you think about any scenario then you need to login first on the facebook page to reach to the home page. So it is better to write all common or repeated step in one place rather than in all scenarios. To achieve this situation we need to add "Background" keyword in the feature file. Let's understand with an example.  

Feature file : home_page_facebook.feature

Feature: In order to test the home page of the application as a registered user  I want to specify the features of the home page. 

Scenario :  Home page default contents.
Given user on application landing page.
When user enter password
And user enter username
And user click on login button 
Then user navigates to application home page.
And user validate default contents of home page

Scenario : Top banner settings option.
Given user on application landing page.
When user enter password
And user enter username
And user click on login button 
Then user navigates to application home page.
When user click on the setting other 
Then user get the logout option


There is 2 scenario where you can see login steps are common to both the scenarios.  So we can eliminate the common section and put it into a commonplace.  

So I am rewriting the feature file with the Background keyword. 


Feature file : home_page_facebook.feature

Feature: In order to test the home page of the application as a registered user  I want to specify the features of the home page. 

Background: Flow till home page 
Given user on application landing page.
When user enter password
And user enter username
And user click on login button 
Then user navigates to application home page.

Scenario :  Home page default contents.
Then user validate default contents of home page

Scenario : Top banner settings option.
When user click on the setting other 
Then user get the logout option

Now you can see login steps are in the commonplace.
There we use Background keyword.  All steps mentioned in the Background keyword will be executed before every scenario or scenario outline. 

I have provided all my glue code and cucumber feature which I have written in eclipse.

cucumber Background keyword

Step definition 

 package com.Cucumber.steps;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import cucumber.api.java.After;  
 import cucumber.api.java.en.Given;  
 import cucumber.api.java.en.Then;  
 import cucumber.api.java.en.When;  
 public class home_page_facebook {  
      WebDriver driver;  
      @Given("^user on application landing page$")  
      public void user_on_application_landing_page() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
           System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");  
           driver = new ChromeDriver();  
           driver.get("http://www.facebook.com/");  
           driver.manage().window().maximize();  
      }  
      @When("^user enter password$")  
      public void user_enter_password() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
           driver.findElement(By.id("pass")).sendKeys("giveourfacebookpassword");  
      }  
      @When("^user enter username$")  
      public void user_enter_username() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
           driver.findElement(By.id("email")).sendKeys("yourusername");  
      }  
      @When("^user click on login button$")  
      public void user_click_on_login_button() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
           driver.findElement(By.id("loginbutton")).click();  
      }  
      @Then("^user navigates to application home page\\.$")  
      public void user_navigates_to_application_home_page() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
        Thread.sleep(3000);  
      }  
      @Then("^user validate default contents of home page$")  
      public void user_validate_default_contents_of_home_page() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
        if(driver.findElement(By.name("q")).isDisplayed())  
        {  
             System.out.println("home page search box diplayed");  
        }else{  
             System.out.println("home page search box not diplayed");  
        }  
      }  
      @When("^user click on the setting other$")  
      public void user_click_on_the_setting_other() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
           driver.findElement(By.id("pageLoginAnchor")).click();  
           Thread.sleep(3000);  
      }  
      @Then("^user get the logout option$")  
      public void user_get_the_logout_option() throws Throwable {  
        // Write code here that turns the phrase above into concrete actions  
        if(driver.findElement(By.xpath("//*[text()='Log out']")).isDisplayed()){  
             System.out.println("logout diplayed");  
        }else{  
             System.out.println("logout not diplayed");  
        }  
      }  
      @After  
       public void tearDown(){  
           driver.quit();  
      }  
 }  


Feature file


 Feature: In order to test the home page of the application as a registered user  
  I want to specify the features of the home page.  
  Background: Flow till home page  
   Given user on application landing page  
   When user enter password  
   And user enter username  
   And user click on login button  
   Then user navigates to application home page.  
  Scenario: Home page default contents  
   Then user validate default contents of home page  
  Scenario: Top banner settings option  
   When user click on the setting other  
   Then user get the logout option  

In my previous cucumber tutorial, I have talked about how to setup cucumber in eclipse and how to run cucumber project. Here is the link

https://www.automation99.com/2017/06/how-to-install-cucumber.html


How to setup Jenkins slave machine




How to setup Jenkins slave machine step by step guide

Jenkins is an open-source automation server, it can be used as automating all kind of task such as building project, testing, deploying project. In software development, DevOps is a very important process nowadays and Jenkins is an essential tool to follow the processes. It is really imported to know how to install Jenkins and set up the Jenkins slave.


Before downloading the Jenkins you need to download and install Java JDK.


Step 1:

Download Jenkins: Jenkins can be downloaded from below link
Jenkins Download

It will download a "jenkins.war" file.

Step 2:

Copy the .war file in a folder. I am copying "jenkins.war" file in my D:/java/ folder.

Step 3:

Open up a terminal in the download directory and run below command

java -jar jenkins.war --httpPort=8080

Here "--httpPort=8080" is optional field. By default, Jenkins runs on 8080 port, but if you want to change the port number then you have to mention the port number as mentioned above.

Step 4:

Once you run the command, Jenkins server starts working and configuration setup starts.

Please find the configuration procedure to setup Jenkins master

Create jenkins master


Step 5:  

Next, we need to setup Jenkins node from Jenkins master. Before creating Jenkins node we need to enable TCP port for JNLP agents. We can enable TCP port for JNLP agents from below steps

1. Click on Manage Jenkins
2. Click on Configure Global Security.
3. Click on the Random radio button beside  "TCP port for JNLP agents". 


Add a new node from Manage Jenkins -> Manage Nodes 

jenkins setup

We need to provide some information about the node. Once we click on the Manage Node link node page will open and we will see "New Node" link.  


Steps for adding a new node. 

1. Click on the New Node
2. Provide the node name 
3.Click on the radio button Permanent agents
4. Click Ok



Now we need to provide below details for newly created node  


Name: < Name of the Node e.g. slave 1>

Description: < Description of the project (This is an optional field)>

# of executors:
The maximum number of concurrent builds that Jenkins may perform on this agent.
The default value is 1.

Remote root directory: This is a mandatory field.


An agent needs to have a directory dedicated to Jenkins. Specify the path to this directory on the agent.
It is best to use an absolute path, such as /var/jenkins or c:\jenkins. This should be a path local to the
agent machine. There is no need for this path to be visible from the master.
e.g. c:\jenkins

Labels:
Labels (or tags) are used to group multiple agents into one logical group.
For example, if you have multiple Windows agents and you have a job that must run on Windows, then
you could configure all your Windows agents to have the label windows, and then tie that job to this
label. 

This would ensure that your job runs on one of your Windows agents, but not on any agents without
this label.

Launch method
Controls how Jenkins starts this agent.


In my tutorial, I am using Launch agent Java Web Start.

I have created one slave with below configuration  


Once we have created slave node we can see newly created slave node displayed under Build Executor Status section on Jenkins home page. But we can see that node as offline mode like below 


How to start Jenkins slave machine 

1.  Open the Jenkins server from slave machine 
Suppose Jenkins server running on 192.168.0.103 and Jenkins port is 8080 then you need to open Jenkins from another machine in the same network with 192.168.0.103.8080. 



2. Provide user name and password. 
3. Click on the Jenkins slave machine (In my case slave 1)
4. Click on the slave.jar hyper link, you will see slave.jar will be downloaded in slave machine.  You just need to copy that jar file into you slave Jenkins directory. I have created Jenkins directory in my d:/jenkins folder.  

5. Open command prompt or cmd and navigate to the folder where you paste or download the slave.jar 


6. Copy the command mentioned in the node 

java -jar slave.jar -jnlpUrl http://localhost:8080/computer/slave1/slave-agent.jnlp -secret e15c60d05ca37d01d593abd6297d6e3f1bb3b9d91c3c97d9155262acea8c61d3 -workDir "d:\jenkins"

You just need to change the ip address. You need to provide master machine ip address where the jenkins server is running. In my case, my server running on 192.168.0.103 and post is 8080 , so command should be
 java -jar <a href="http://192.168.0.103:8080/jnlpJars/slave.jar" style="box-sizing: border-box; color: #5c3566; word-wrap: break-word;">slave.jar</a> -jnlpUrl http://192.168.0.103:8080/computer/slave1/slave-agent.jnlp -secret e15c60d05ca37d01d593abd6297d6e3f1bb3b9d91c3c97d9155262acea8c61d3 -workDir "d:\jenkins"  

7. Paste the command in command prompt. and hit enter 
  

8 . Afer successfully executed the command Jenkins slave will be online.


How to highlight elements in WebDriver during runtime

How to highlight elements in WebDriver during runtime

In web automation-testing, element highlighter plays a very important role. It helps to track the exact step to be performed.  UFT/QTP like testing tool is capable to highlight an element in run time because you will get this feature inbuilt with this tool. In Selenium there is no such feature available so we need to write our own code to highlight element.

  
Highlighting element is also useful for debugging the code.One way to know steps being performed in the browser is to highlight the web page elements.

The core to use "JavaScriptExecutor" to inject javascript in your application and change the CSS for the element, like create a border for the element. 

Sample code 
 JavascriptExecutor js=(JavascriptExecutor)driver;   
 js.executeScript("arguments[0].style.border='4px groove red'", Element);  

Explanation  

Arguments[0].style.border:- this script is injecting the CSS style tag into the element and making its border settings with a 4px wide red line with groove look.

Element: - This is the element around which border will be drawn.

I am creating a method which could be reusable for highlighting the test element. 

Element Highlight method 


 public void HighlightElement(WebDriver driver, WebElement elm){  
           try{  
                JavascriptExecutor js=(JavascriptExecutor)driver;   
                js.executeScript("arguments[0].style.border='4px groove red'", elm);  
          Thread.sleep(1000);  
          js.executeScript("arguments[0].style.border=''", elm);  
           }catch(Exception e){  
                System.out.println(e);  
           }  
      }px groove red'", email);  


Video



Complete code


 package com.selenium.sampleseleniumproject;  
 import org.testng.annotations.Test;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.JavascriptExecutor;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class AppTest3 {  
      protected WebDriver driver;  
      @Test  
      public void Highlight() throws InterruptedException {  
           System.setProperty("webdriver.chrome.driver",  
                     "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");  
           driver = new ChromeDriver();  
           driver.get("http://www.faceboo.com");  
           driver.manage().window().maximize();  
           WebElement email = driver.findElement(By.xpath("//*[@id='email']"));  
           WebElement pass = driver.findElement(By.xpath("//*[@id='pass']"));  
           HighlightElement(driver, email);  
           email.sendKeys("[email protected]");  
           HighlightElement(driver, pass);  
           pass.sendKeys("password");  
           // close browser  
           driver.close();  
      }  
      public void HighlightElement(WebDriver driver, WebElement elm) {  
           try {  
                JavascriptExecutor js = (JavascriptExecutor) driver;  
                js.executeScript("arguments[0].style.border='4px groove red'", elm);  
                Thread.sleep(1000);  
                js.executeScript("arguments[0].style.border=''", elm);  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
      }  
 }  

How to do scroll action till the particular element is present in appium


How to do scroll action till the particular element is present in appium ?


How to do scroll action till the particular element is present or not
I am currently working on appium for automating WhatsApp mobile application. I needed one method which would perform the ‘scroll’ action to a particular name or number and choose to click on a particular name or number. So I googled for that method and I found out that there are two methods, scrollTo(), scrollToExact(), which was supposed to solve my problem. But when  I started writing the code and again I faced another problem.  I am using appium java client 5.0.0-BETA9 (updated version )and on this version, there are no such methods like scrollTo() or scrollToExact().  Previously I had worked on the seetest tool and it is a mobile automation tool, there was a method called ‘swipewhileNotFound’ which would scroll the app view until the desired object was visible.  SeeTest is a licensed tool. Hence there are several readymade methods available for automating mobile application.  So I started writing this method for appium because I needed this method for appium to work.


I have used TestNG to write the test, but you can use any testing framework or simple Java class with the method mentioned above. I have posted my code here so that you can have a look at it. Also, you can download the complete java file from the below link


How to do scroll action till the particular element is present or not

 package appium;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.Dimension;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.remote.DesiredCapabilities;  
 import org.testng.annotations.*;  
 import io.appium.java_client.android.AndroidDriver;  
 public class WhatsAppAutomate {  
 // WebDriver driver;  
 protected AndroidDriver driver;  
 @BeforeClass  
  public void setUp() throws MalformedURLException {  
  DesiredCapabilities capabilities = new DesiredCapabilities();  
  capabilities.setCapability("deviceName", "8fe5de4a");  
  capabilities.setCapability("platformName", "Android");  
  capabilities.setCapability("appPackage", "com.whatsapp");  
  // This package name of your app (you can get it from apk info app)  
  capabilities.setCapability("appActivity", "com.whatsapp.Main");   
  driver = new AndroidDriver(new URL("http://192.168.0.102:5036/wd/hub"), capabilities);  
 }  
  @Test  
  public void testCal() throws Exception {  
  swipeWhileNotFound("down","//*[@text='Anjan Mondal']",1000,3000,3000,17,true);  
  }  
  public void swipeWhileNotFound(String direction, String xpath,int offset,int waitTime,int duration,int round, boolean click) throws InterruptedException {  
   Dimension size = driver.manage().window().getSize();  
  int startx = size.width/2;  
  int starty=0;  
  int endy=0;  
  try {  
  driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);  
  boolean loop = true;  
  int count = 0;  
  while (loop) {  
  if (count == round) {  
  System.out.println("round over");  
  break;  
  }  
  if (driver.findElements(By.xpath(xpath)).size() > 0) {  
  loop = false;  
  System.out.println("element found");  
  WebElement elm = driver.findElement(By.xpath(xpath));  
  if (click)  
  elm.click();  
  } else {  
  if(direction.toUpperCase().equals("UP")){   
  starty=size.height-offset;  
  endy = (int) (size.height * 0.60);  
  driver.swipe(startx, starty, startx, endy, duration);  
  Thread.sleep(waitTime);  
  }else if(direction.toUpperCase().equals("DOWN")){  
  starty = (int) (size.height * 0.80);   
  endy= offset;  
  driver.swipe(startx, endy, startx, starty, duration);  
  Thread.sleep(waitTime);  
  }   
  count++;  
  }  
  }  
  } catch (Exception e) {  
  System.out.print(e);  
  } finally {  
  driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);  
  }  
  }  
  @AfterClass  
  public void teardown() {  
  // close the app  
  driver.quit();  
  }  
 }  

How to use chrome headless using selenium

How to use chrome headless using selenium

How to use chrome headless using selenium  


A headless browser is a kind of web browser which has no user interface, In other words,  a browser, that access web pages but doesn’t show them to any human being. They’re actually used to provide the content of web pages to other programs. 



Why is that useful?



A headless browser is a great tool for automated testing and server environments where you don't need a visible UI shell. For example, you may want to run some tests against a real web page, create a PDF of it, or just inspect how the browser renders an URL.

Now Chrome also supports headless feature from version 59 .  

Right now, Selenium opens a full instance of Chrome. In other words, it's an automated solution but not completely headless. However, Selenium could use --headless in the future.


There are few bugs  in new chrome driver so we need to use 2 chromeOptions to use headless Chrome in selenium  

Here is code for chrome headless  in windows system 

 import org.junit.Assert;  
 import org.junit.Test;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.chrome.ChromeOptions;  
 import org.openqa.selenium.support.ui.ExpectedConditions;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
 import java.io.IOException;  
 public class HeadlessChrome  
 {  
  @Test  
  public void createChromeDriverHeadless() throws IOException  
  {  
    ChromeOptions chromeOptions = new ChromeOptions();  
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver_win32\\chromedriver.exe");  
    chromeOptions.addArguments("--headless");  
    chromeOptions.addArguments("--disable-gpu");  
    WebDriver Driver = new ChromeDriver(chromeOptions);  
    Driver.navigate().to("https://www.facebook.com");  
    WebDriverWait waitForUsername = new WebDriverWait(Driver, 5000);  
    waitForUsername.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));  
    Driver.findElement(By.id("email")).sendKeys("tomsmith");  
    Driver.findElement(By.id("loginbutton")).click();  
    WebDriverWait waitForError = new WebDriverWait(Driver, 5000);  
    waitForError.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));  
    Assert.assertTrue(Driver.findElement(By.id("loginbutton")).getText().contains("Log In"));  
    Driver.quit();  
  }  
 }  

How to create maven project in eclipse for selenium



how to create maven project in eclipse for selenium

How to create maven project in eclipse for selenium

In my earlier post I have discussed about maven tool on automation front.  I have also discussed about whats is POM and why we use maven tool for java project .  In this post I will create one sample selenium project using maven. Before creating the maven project we need to download and install maven.  I am assuming you  have JAVA and eclipse IDE installed in your machine.

Prerequisite 

  1. Download Maven LINK.
  2. Install maven .
  3. Add M2_HOME and MAVEN_HOME in the Windows environment, and point it to your Maven folder.
  4. Add Path
  5. Verify
  6. Install maven plugin in your eclipse.  
1. Download Maven

You can download maven from the below link.  
2. Install maven .

There is no installation file. You just need to download the archive file and extract in tour hard drive. Assuming you have extract the folder in C:\Program Files\Apache\maven

maven folder after unzip


3. Add M2_HOME and MAVEN_HOME

Add M2_HOME and MAVEN_HOME variable in windows environment.

M2_HOME should be C:\Program Files\Apache\maven
MAVEN_HOME should be C:\Program Files\Apache\maven


4.  Add Path
You need to Update PATH variable, append Maven bin folder – %M2_HOME%\bin, so that you can run the Maven’s command everywhere.

5. Verify

Run the below command to know that maven installed and configured in your system properly or not. If you see the version and maven home after executing the command it means maven configured properly. 

Maven command 

mvn –version in the command prompt/cmd

6. Install maven plugin in your eclipse. 

You need to download eclipse maven plugin from eclipse marketplace.
Maven plugin for eclipse

Or if you really don't want to do this above mentioned steps to configure maven in your system there is another simple way to solve this problem.You just need to download maven enabled eclipse from the eclipse website. Here is the link below for eclipse luna with eclipse integration .


Till now we have configured the maven environment.  Now we will create selenium project with maven 

Step 1:  Create maven project from eclipse IDE 

Go to File -> Project -> Maven -> Maven Project 

Next screen will ask for your project location where you want to create the project.  You can use Default Workspace location. 


Step 2:  Select Archetype 

 In the next screen, It will ask you to select an Archetype. Depending on the type of project that you are working, you need to choose the archetype


Step 3:  Enter a group id for the artifact

Now you need to enter a group id for the artifact, artifact id ,version and package,
We will input as shown in the below image. Version number will be by default 0.0.1-SNAPSHOT


Step 4: Finish step

After clicking finish button the maven project will be created with maven structure. It will create one sample POM also.

Sample POM look like this

Step 4: Edit POM file and add selenium dependency 

Copy the selenium dependency XML from maven central. or you can also get the XML from selenium org web site


  1. selenium website  -  LINK http://docs.seleniumhq.org/download/maven.jsp


    2. maven central   - LINK


Edit the POM XML file for the project and add the selenium dependency 



Step 6: Save the project using CTRL+S

Once you save the project it maven start building the project. Means maven start pulling all required dependency  from the maven central.

You can build the project using build maven command. you can set the goal as compile.


Step 7:  Navigate to src/test/java 

If you navigate to src/test/java folder , you will see there is class call AppTest . You can use this call for writing test case or you can create different class file per your requirement. 

I have created separate  class file called "TestCode" under src/test/java folder. I am using junit for writing test.  If you look into the POM file , you will see junit is already added in the dependency.  If you observe junit is not added in your POM file then you need to add the dependency for junit. 



Step 8:  Run the Junit test

Run the test in junit you will see chrome will open and navigate to facebook page . In my previous post I have mentioned how to open chrome in selenium. 


download maven selenium projectDownload sample maven selenium  Project 


Basic of maven tool on Automation front



Basic of maven tool on Automation front


A build tool is a tool that automates everything related to building the software project. Maven, is an innovative software project management tool, provide new concept of a project object model(POM) file to manage project's build , dependency and documentation, this session is to target the beginners in helping them understand the basic of maven tool on Automation front

 Why Automation Build Tool 

  1. Accelerate the compile and link processing.
  2. It will minimize the human errors while building a software.
  3. Reduce redundant tasks.
Maven is a 
  1. Building tool.
  2. Dependency management tool
  3. Project management tool  
Core concept in Maven depends on following points 
  1. Dependencies and repositories 
  2. Build Life Cycle 
  3. Phases
What is Dependencies

Dependencies are required jars which are required to build the project.
Include all Jars and plugins in project.

Maven Repository 

3 types of maven repository 
  1. Local Repository : Local repository is a folder location in development machine and it gets crated when you run any maven command for the first time. (By default folder name is .m2)
  2. Central Repository : Maven central repository is repository provided by Maven community. It contains a large number of commonly used libraries.  http://repo1.maven.org/maven2/
  3. Remote repository :Some time maven dose not find required file in central and due to this build process gets failed.  To overcome this problem Maven provides concept of Remote Repository which is developer's own custom repository containing required libraries or other project jars.  
Sample POM for Remote repository 

how to use Remote repository in POM

Build Life Cycle

Maven has mainly 3 build in life cycles
  1. Clean
  2. Site
  3. Default
What is POM 
A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project
  • Maven reads POM file to build the project. 
  • Specifies project information, plugins, goals, dependencies and profiles. 
Sample POM 


Sample pom for cucumber


Sample project structure for Maven project  


maven project sample

In my next post I'll explain how to configure MAVEN project and sample selenium maven project. 

Cucumber scenario outline with examples


Cucumber scenario outline with examples


Scenario outline basically replace the value with the datatable value.  Here each row of the data table consider as a new scenario.  For example suppose I want to login into the www.facebook.com site.  As of now we have execute only one scenario. We have provided username and password for login into the facebook site.  If you closely look into the site you can see there 3 different ways to login into the application.

  • We cant provide email id and password.
  • We can provide phone number and password.
  • We can provide user name and password. 
Now we can achieve above mentioned scenarios in 3 different scenario with 3 different input type 

Scenario 1:

Feature: Login Application
  As a user
  I want to login to the application

  Scenario: Valid user email id and password
    Given I launch the url "https://www.fb.com"
    When I enter password and email
    And I click on login button
    Then I should see the login page

Scenario 2:


Feature: Login Application
  As a user
  I want to login to the application

  Scenario: Valid user phone number and password
    Given I launch the url "https://www.fb.com"
    When I enter password and phone no.
    And I click on login button
    Then I should see the login page

Scenario 3:

Feature: Login Application
  As a user
  I wa
  Scenario: Valid user name and password
    Given I launch the url "https://www.fb.com"
    When I enter password and username
    And I click on login button
    Then I should see the login pagent to login to the application

Here you can see the scenario statements are same for all there scenario, only difference is that the parameter(user name / phone number/ email id). Here is the scenario outline feature comes into the picture. 

We can design this login feature in such a way where  scenario will be only one but test data will be 3 and the scenario will be execute 3 times. 

Till now we have used Scenario keyword in feature file but iteration purpose we should use Scenario Outline instead of Scenario.


Feature file : ScenarioOutline.feature

Feature: Login Application
  As a user
  I want to login to the application

  Scenario Outline: Valid user name and password
    Given I launch the url "https://www.fb.com"
    When I provide "<username>" and "<password>"
    And I click on login button
    Then I should see the login page

    Examples: 
      | username          | password |
      |        987654210 | [email protected] |
      | username1          | [email protected] |

Here the Examples annotation  describe the range of iteration , means how many times the test case will execute. In this example the test case will execute 3 times.

Complete steps 
 package com.Cucumber.steps;  
 import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebDriverException;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.testng.Assert;  
 import cucumber.api.DataTable;  
 import cucumber.api.Scenario;  
 import cucumber.api.java.After;  
 import cucumber.api.java.en.Given;  
 import cucumber.api.java.en.Then;  
 import cucumber.api.java.en.When;  
 public class DemoLoginSteps2 {  
  WebDriver driver;  
  @Given("^I launch the url \"([^\"]*)\"$")  
  public void i_launch_the_url(String arg1) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");  
  driver = new ChromeDriver();  
  driver.get("https://www.fb.com");  
  }  
  @When("^I provide \"([^\"]*)\" and \"([^\"]*)\"$")  
  public void i_provide_and(String arg1, String arg2) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  driver.findElement(By.name("email")).sendKeys(arg1);  
  driver.findElement(By.name("pass")).sendKeys(arg2);  
  }  
  @When("^I click on login button$")  
  public void i_click_on_login_button() throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  driver.findElement(By.xpath("//*[@data-testid='royal_login_button']")).click();  
  }  
  @Then("^I should see the login page$")  
  public void i_should_see_the_Error_message() throws Throwable {  
  try{  
    // Write code here that turns the phrase above into concrete actions  
   if(driver.findElement(By.name("email")).isDisplayed()){  
   Assert.assertTrue(true);  
   }else  
   Assert.assertTrue(false);  
  }catch(Exception NoSuchElementException){  
   Assert.assertTrue(false);  
  }finally{  
   driver.quit();  
  }    
  }  
 }  


You can run the test from feature file or from testng xml. If you want to execute using testng the you need to write runner class first and then testng xml.

Runner class
 package com.Cucumber.Runners;  
 import cucumber.api.CucumberOptions;  
 import cucumber.api.testng.AbstractTestNGCucumberTests;  
 @CucumberOptions(  
  features = "src/com/Cucumber/features/ScenarioOutline.feature",   
  glue = "com.Cucumber.steps",   
  plugin = { "pretty", "html:target/cucumber-report" },   
  monochrome = true)  
 public class RunTest extends AbstractTestNGCucumberTests {  
 }  


TestNgXML







How to use Datatable in cucumber


How to implement Datatable in cucumber

How to use Datatable in Cucumber


In my previous post How to install and configure cucumber -java  I have discussed how to install Cucumber and how to run cucumber program in java. In the previous post, I did not show how to parameterize the data. Means previously we passed parameters in the step line. Now we declared the variable in the feature file. So we are using Tables as arguments to Steps. 

I have created one feature file named: dataDriven.feature under com.Cucumber.features package.

how to user cucumber datatable

dataDriven.feature is almost same as the previous demo.feature . The only difference is the "when" .
previously it was " When I enter password and username" and now 

When I provide password and username
      | testname | [email protected] |




dataTable feature file 
 Feature: Login Application  
  As a user  
  I want to login to the application  
  Scenario: Valid user name and password  
   Given I launch the url "https://www.fb.com"  
   When I provide password and username  
    | testname | [email protected] |  
   And I click on login button  
   Then I should see the login page  

Now we need to write down the step file. As you see there are very few changes in scenario/feature file so we can re use all the methods except the step written under "@when"

The implementation of the @when step


 @When("^I provide password and username$")  
  public void i_enter_password_and_username(DataTable rawdata) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  List<List<String>> data = rawdata.raw();  
  driver.findElement(By.name("email")).sendKeys(data.get(0).get(0));  
  driver.findElement(By.name("pass")).sendKeys(data.get(0).get(1));   
  }   


The complete steps 

 package com.Cucumber.steps; import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.OutputType;  
 import org.openqa.selenium.TakesScreenshot;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebDriverException;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.testng.Assert;  
 import cucumber.api.DataTable;  
 import cucumber.api.Scenario;  
 import cucumber.api.java.After;  
 import cucumber.api.java.en.Given;  
 import cucumber.api.java.en.Then;  
 import cucumber.api.java.en.When;  
 public class DemoLoginSteps {  
  WebDriver driver;  
  @Given("^I launch the url \"([^\"]*)\"$")  
  public void i_launch_the_url(String arg1) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");  
  driver = new ChromeDriver();  
  driver.get("http://www.fb.com");  
  }  
  @When("^I click on login button$")  
  public void i_click_on_login_button() throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  driver.findElement(By.xpath("//*[@data-testid='royal_login_button']")).click();  
  }  
  @Then("^I should see the login page$")  
  public void i_should_see_the_Error_message() throws Throwable {  
  try{  
    // Write code here that turns the phrase above into concrete actions  
   if(driver.findElement(By.name("email")).isDisplayed()){  
   Assert.assertTrue(true);  
   }else  
   Assert.assertTrue(false);  
  }catch(Exception NoSuchElementException){  
   Assert.assertTrue(false);  
  }finally{  
   driver.quit();  
  }  
  }  
  @When("^I provide password and username$")  
  public void i_enter_password_and_username(DataTable rawdata) throws Throwable {  
    // Write code here that turns the phrase above into concrete actions  
  List<List<String>> data = rawdata.raw();  
  driver.findElement(By.name("email")).sendKeys(data.get(0).get(0));  
  driver.findElement(By.name("pass")).sendKeys(data.get(0).get(1));   
  }  
 }  




If you want to execute cucumber test from testng xml or just left click on feature file and Run As Cucumber Feature.


How to install and configure cucumber -java

How to install Cucumber - java in eclipse

How to install cucumber java?

Prerequisite for installing Cucumber 


1. jdk (Latest jdk recomanded).
3.Eclipse plugins

   i. TestNG plugin - http://beust.com/eclipse
   ii. Cucumber eclipse plugin - http://cucumber.github.com/cucumber-eclipse/update-site

You need to download few cucumber related jars.

1. cucumber-core-1.2.5
2. cucumber-html-0.2.3
3. cucumber-java-1.2.5
4. cucumber-jvm-deps-1.0.5
5. cucumber-testng-1.2.5
6. gherkin-2.12.2
7. selenium-server-standalone-3.4.0
8. testng-6.11


To configure cucumber java you need to follow few steps

Step 1  :  Open eclipse and configure workspace 

how to install cucumber- java

Step 2  : Create a new project in eclipse  

You can create an new project from File > New >Java Project . You need to provide a name for that project , say "TestCucumber" and tap on Finish button. You will find "TestCucumber" is created in left side panel of eclipse IDE. 

how to install cucumber- java



Step 3 :  Configure java build path from eclipse .

You need to configure java build path . Means you need to add TestNG library and required external jars with this new project. 

a. Left click on the project. 



b.  Click on the Build Path > Configure Build Path ..




c.  Click on Add library and and TestNG and Click Next > Finish . TestNG will be added for this project.



d. Click on Add External JARs,, and navigate to downloaded location where there cucumber related jars are there. 

add external jars for cucumber

e.  Click on Open the Click on Ok button .. All required jars will be added with the project.

Step 4:  Create 3 package in side the TestCucumber/src 

a.  com.Cucumber.features :  This package consist all feature files. 
b  com.Cucumber.steps : Actual java program where selenium steps are written. 
c. com.Cucumber.Runners : This file consist configuration for the test. 

There I am creating a sample Cucumber project 

Sample feature file

Feature: Login Application
  As a user
  I want to login to the application

  Scenario: Valid user name and password
    Given I launch the url "http://www.fb.com"
    When I enter password and username
    And I click on login button
    Then I should see the Error message

You need to create a file under com.Cucumber.features package . File extension should be .feature
Cucumber feature file


Name of the sample feature file is demo.feature

Now you need to create actual selenium file under com.Cucumber.steps package.

Sample step java file 


package com.Cucumber.steps;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class DemoLoginSteps {
 WebDriver driver;
 @Given("^I launch the url \"([^\"]*)\"$")
 public void i_launch_the_url(String arg1) throws Throwable {
     // Write code here that turns the phrase above into concrete actions
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");
  driver = new ChromeDriver();
  driver.get("http://www.fb.com");
     
 }

 @When("^I enter password and username$")
 public void i_enter_password_and_username() throws Throwable {
     // Write code here that turns the phrase above into concrete actions
  driver.findElement(By.name("email")).sendKeys("test");
  driver.findElement(By.name("pass")).sendKeys("cucumber");
  
 }

 @When("^I click on login button$")
 public void i_click_on_login_button() throws Throwable {
     // Write code here that turns the phrase above into concrete actions
 driver.findElement(By.xpath("//*[@data-testid='royal_login_button']")).click();
 }

 @Then("^I should see the login page$")
 public void i_should_see_the_Error_message() throws Throwable {
  try{
     // Write code here that turns the phrase above into concrete actions
   if(driver.findElement(By.name("email")).isDisplayed()){
    Assert.assertTrue(true);
   }else
    Assert.assertTrue(false);
  }catch(Exception NoSuchElementException){
    Assert.assertTrue(false);
  }finally{
   driver.quit();
  }
     
 }

}


Name of the step file is DemoLoginSteps

You can generate step code automatically, but you need to clear few lines of code like " throw new PendingException(); "from each methods and you need to write down the actual  selenium steps as per your requirements. Auto generated file is nothing but a skeleton of the methods.

How to generate step file automatically 

You just need to left click on the feature file and click on the Run As Cucumber feature . You will file unimplemented methods are displayed on eclipse console screen.
How to generate test step in cucumber
Create a RunTest Class under om.Cucumber.Runners package (You need to create om.Cucumber.Runners package under src folder)

Sample runner class


CucumberOptions(
     features = "src/com/Cucumber/features/Login.feature", 
     glue = "com.Cucumber.steps", 
     plugin = { "pretty", "html:target/cucumber-report" }, 
     monochrome = true)

public class RunTest extends AbstractTestNGCucumberTests {

}
Name of runner class is RunTest

How to write runner class using testng


feature  : Location of feature file in your project
glue : package name for the step java file
plugin : Reporting purpose
monochrome :This option can either set as true or false. If it is set as true, it means that the console output for the Cucumber test are much more readable. And if it is set as false, then the console output is not as readable as it should be. For practice just add the code ‘monochrome = true‘ in TestRunner class.

Create a testng file under project to run the RunTest file.

Testng XML

Cucumber with testng

You can run the test case without writing the xml file but testng xml will help you to create CI integration very easily.

How to run test case without testng xml 

 You need to run left click on the feature file and choose Run As Cucumber Feature.

How to run test case using testng xml

You just need to left click on the testng xml file and choose Run As TestNG suite.


your ad