Sunday 27 March 2016

Running Selenium tests using Jenkins and GIT

We can run selenium tests using Jenkins very easily.

How to set up Jenkins?
  1. Download Jenkins.
  2. Install git client
  3. Set up maven task
Configuring Jenkins and running selenium tests
Jenkins server can be accessed @ localhost:8080
Please have a look at below images of Jenkins server.

  1. Go to localhost:8080 to open Jenkins Home screen
  2. Then configure JDK and Maven
  3. Then install git plug-in
  4. Then create new maven job
  5. In maven job configuration, specify the git details (git url where your selenium tests are kept) and build trigger.
  6. Then Specify Maven goal
  7. Once Job is saved, you can manually run it or wait until it gets triggered automatically.
  8. When the job is running, you can view the console output as well.

Jenkins Server Home Screen



Jenkins Server - JDK Configuration



Jenkins Server - Maven Configuration



Jenkins Server - Manage Plug-ins

Jenkins Server - Install Git Plug-ins


Jenkins Server - Create new Maven Project








Jenkins Server - GIT configuration




Jenkins Server - Build trigger and goal

Jenkins Server - Running build




Jenkins Server - Console output




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Cucumber with Selenium Webdriver in Java

Cucumber is one of the most popular BDD testing frameworks. In this article, you will learn how to write the feature files and step definitions for running Selenium tests.

What tools you will need to run cucumber tests?

  1. JAVA IDE - Intellij IDEA 
  2. JDK
  3. Maven or Gradle
  4. Cucumber API
  5. Cucumber plug-in for Intellij IDEA
  6. Intellij IDEA plug-ins for Gherkin and Cucumber for Java
You will need to add below dependencies in your project to use Cucumber API


testCompile 'info.cukes:cucumber-java:1.2.4'testCompile 'info.cukes:cucumber-junit:1.2.4'

How to write tests using Cucumber?
Below example shows how you can write a simple cucumber test class. When we run that Test class, all features in the src/test/resources directory are run. If there are no step definitions written for the steps in feature file, it creates sample step methods for you.

package cucumber_tests;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

/** * Created by Sagar on 27-03-2016. */
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/")
public class CucumberTests {
}

I had a feature file as shown below. But I did not write any steps.

Feature:Simple Selenium test
  Scenario: To check page loading
    Given I am on "http://www.softpost.org" home page
    When I click on "Selenium Test page" link
    Then I land on Selenium Test Page

so after running above class, in the console I noticed that sample step methods are created.

1 Scenarios (1 undefined)
3 Steps (3 undefined)
0m0.000s

You can implement missing steps with the snippets below:

@Given("^I am on \"([^\"]*)\" home page$")
public void i_am_on_home_page(String arg1) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I click on \"([^\"]*)\" link$")
public void i_click_on_link(String arg1) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I land on Selenium Test Page$")
public void i_land_on_Selenium_Test_Page() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

Process finished with exit code 0.

After that I just copied all these methods and pasted into the steps class . Then I updated all test methods.

package steps;

import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.runtime.junit.FeatureRunner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

/** * Created by Sagar on 27-03-2016. */public class step_definitions {
    WebDriver driver;
    @Before    public void init(){
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }

    @Given("^I am on \"([^\"]*)\" home page$")
    public void i_am_on_home_page(String arg1) throws Throwable {
        driver.get("http://www.softpost.org");
    }

    @When("^I click on \"([^\"]*)\" link$")
    public void i_click_on_link(String arg1) throws Throwable {
        driver.findElement(By.linkText("Selenium Test Page")).click();
    }

    @Then("^I land on Selenium Test Page$")
    public void i_land_on_Selenium_Test_Page() throws Throwable {
      assert driver.findElements(By.id("fn")).size() > 0;
    }

    @After    public void clean() {
        driver.close();
        driver.quit();
    }
}


After that I ran the test class but still Cucumber was unable to find the step definitions. Then I updated cucumber options as described below.

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/resources",
        glue = {"steps"}
)

Notice that how I have added glue in the cucumber options. This is important to note that glue should be configured to be the package name in which your step definitions exist. While features option can have the value as directory name.

Another thing to note is that we can use lambda expressions to write step definitions. But for that you will have to use Java 8.
You may encounter below error when working with lambda expressions.
invalid method declaration return type required cucumber
To fix this error, you need to use below syntax.

public class lambda_steps implements En {
    public lambda_steps() {

        Given("^I am on softpost\\.org home page$", () -> {

        });
 }
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday 26 March 2016

Writing JUnit tests with Selenium Webdriver

JUnit framework is a popular unit testing framework in Testing world.

In this article, you will get to know how to write junit tests with selenium webdriver. All you need to write the JUnit tests is JUnit provider. Just add that dependency in your Java project and start writing the tests.

How to add JUnit dependency in your project?


Most of the maven and Gradle projects POM and build.gradle file is created with JUnit dependency automatically when you create such projects. But in case your POM.xml file does not have JUnit dependency, just add below lines in dependencies section your POM.xml

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>


If you are using Gradle based project, just add below line in build.gradle file. 

testCompile group: 'junit', name: 'junit', version: '4.11'

How to write JUnit tests for Selenium Webdriver?

We need to create a Class and methods in it annotated with @Test as shown in below example. You can execute this test by pressing CTRL+SHIFT+F10 in Intellij IDEA or you can just right click on the method and click on Run using JUnit.

public class FirefoxTests {

    static WebDriver driver;

    @Test    public void launchChrome() throws Exception{
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://www.softpost.org/selenium-test-page/");
        driver.close();
        driver.quit();
    }
}

Executing Selenium JUnit tests with Maven
You can also run JUnit tests using Maven Goals. Maven uses Surefire plug-in to run the tests during Test phase. You can also configure the Surefire plug-in to include or exclude the specific tests.
Just type below command in command prompt and all your tests will get executed.

mvn test

If you want to run specific tests, you can pass -Dtest parameter which runs tests in specific class. Say you want to run tests in only BookingTests class, then use below command.

mvn test -Dtest=BookingTests

Executing Selenium JUnit tests with Gradle
You can also run JUnit tests using Gradle tasks.
Just type below command in command prompt and all your tests will get executed.

gradle test

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Data driven frameworks in Selenium Webdriver

There are various types of Automation frameworks in the automation testing world as mentioned @Softpost.org

One of them is Data driven framework. This kind of framework is used when we need to test same application flows using different combinations of data. Different types of applications need different types of frameworks. We must use Data driven framework in a situation where there are limited number of Application flows but there is wide variety of data that is consumed by application.

For example - Consider a simple register functionality of a website. You need to verify that password should meet below criteria.

  1. At least 8 characters in length
  2. Should contain alphanumeric characters
  3. Should contain at least one non-alphanumeric character.
  4. Should contains at least one lower case and one upper case letter.
All we need to do to test this functionality is write simple test which will enter values in the password textbox and verify if the password test passes. In this scenario, all steps are same except test data. That is when we should Data driven frameworks. We can store data in either excel sheet or database.
Test reads each set of data and repeats same steps.

The main difference between keyword driven and data driven frameworks is that in keyword driven frameworks we have multiple application flows and operations. Generally, in most of the projects hybrid frameworks are used as application has multiple flows and various combinations of data at the same time.



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Page Factory Model in Selenium Automation

There are several automation frameworks as described @softpost.org. Page Factory model is one of the most popular selenium automation framework.

Key features of Page Factory model

  1. Object oriented
  2. Most of the features are similar to Page Object Models
  3. One primary difference between page object model and page factory model is that web elements are initialized in different manner.

Here is the sample Page class for a page @Softpost.org

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import pages.common.BasePage;

public class SeleniumTestPageUsingFactory extends BasePage {

    public SeleniumTestPageUsingFactory(WebDriver driver){
        super(driver);
        PageFactory.initElements(driver,this);
    }

    @FindBy(id = "fn" )
    WebElement firstName;

    public void setFirstName(String name){
        firstName.sendKeys(name);
    }

    public String getFirstName(){
        return firstName.getAttribute("value");
    }

}

Note how we have used PageFactory.initElements method to initialize the elements on the page.

We can instantiate this page class and perform operations on Page elements. Below class demonstrates how we can use this Page class in tests.

package page_object_model_tests;

import org.junit.Assert;
import org.junit.Test;
import page_object_model_tests.BaseTests.BaseTest;
import pages.SeleniumTestPage;
import pages.SeleniumTestPageUsingFactory;

public class SamplePageTestsUsingFactory extends BaseTest {

    @Test    public void testPage() {
     SeleniumTestPageUsingFactory seleniumTestPage;
     seleniumTestPage  = new SeleniumTestPageUsingFactory(driver);
     seleniumTestPage.setFirstName("Sagar");
     String name = seleniumTestPage.getFirstName();
     Assert.assertTrue("Name validation",name.equalsIgnoreCase("Sagar"));
    }
}

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Friday 25 March 2016

Page object models in Selenium Webdriver frameworks

There are various frameworks that can be used in Automation as mentioned
@ Softpost.org.

One of them is Page object model which is specially used in Selenium Automation.

Major features of Page Object models are
  1. It's a object oriented framework.
  2. All application pages are modeled as Page classes. Each Page class has fields (Elements on the page). Each Page class has methods that get or set the values for the elements. This helps in the maintenance of the project as elements are not duplicated.
  3. Step classes are created which can use multiple page models to  perform specific operation like login, book a ticket, cancel a ticket, log out etc.
  4. Test classes contain test methods which use Step classes to automate the test flow. From test class, we pass on the input data to steps classes and steps classes pass that data to page classes.
Architectural diagram of Page Object models



Example in Java - Page Object models

Just imagine that you have a website www.softpost.org and you want to design the Page object model framework for that website.

Steps to create page object models -
  1. Identify all pages in the application and create a class for each page.
  2. Identify elements and create methods to access to those elements.
  3. Write the Step class to use one or multiple Page classes. This step class is optional as We can access the Page members directly from Tests by instantiating the Page classes.
  4. Then write the Test classes that uses steps to develop the test case.
For example - Consider this Selenium Test page 

So sample page class for this page will look like below.

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import pages.common.BasePage;

public class SeleniumTestPage extends BasePage {

    private String firstName="//td[contains(text(),'First Name')]" +
            "//following-sibling::td//input";

    public SeleniumTestPage(WebDriver driver){
        super(driver);
        driver.get("http://www.softpost.org/selenium-test-page/");
    }

    public void setFirstName(String name){
    driver.findElement(By.xpath(firstName)).sendKeys(name);
    }

    public String getFirstName(){
    return driver.findElement(By.xpath(firstName)).getAttribute("value");
    }

}

We can create instances of this class from our test and then perform any operation on that page.

package page_object_model_tests;

import org.junit.Assert;
import org.junit.Test;
import page_object_model_tests.BaseTests.BaseTest;
import pages.SeleniumTestPage;

public class SamplePageTests extends BaseTest {

    @Test    public void testPage() {
     SeleniumTestPage seleniumTestPage = new SeleniumTestPage(driver);
     seleniumTestPage.setFirstName("Sagar");
     String name = seleniumTestPage.getFirstName();
     Assert.assertTrue("Name validation",name.equalsIgnoreCase("Sagar"));
    }
}

Above test will create the object of Page - SeleniumTestPage and then use it's methods to interact with elements on the page.
Below code shows the BaseTest class. All tests inherit from this class.


package page_object_model_tests.BaseTests;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;

public class BaseTest {
    protected static WebDriver driver ;
    @BeforeClass    public static void init() {
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }
    @AfterClass    public static void clean() {
        driver.close();
        driver.quit();
     }
} 

Below code shows the BasePage class. All pages inherit from this base page class.

import org.openqa.selenium.WebDriver;

/** * Created by Sagar on 26-03-2016. */public class BasePage {
    protected WebDriver driver;

    public BasePage(WebDriver driver){
        this.driver = driver;
    }

    //Common methods will be put here
}

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

What is fluent wait in Selenium Webdriver

Fluent wait is used to synchronize the elements in the browser.

Fluent wait allows you to
  1. Specify polling time
  2. Maximum time out
  3. Ignore Exceptions
Consider a scenario wherein you are expecting specific element to appear within 20 seconds. Time to load that element might change from 5 seconds to 20 seconds. In this situation, we can use Fluent Wait as mentioned in below example.

@Test
public void testWait(){
  String driverpath = 
  System.setProperty("webdriver.chrome.driver""C:\\chromedriver.exe");
  driver = new ChromeDriver();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  driver.get("http://www.softpost.org/selenium-test-page/");

  Wait wait = new FluentWait(driver)
            .withTimeout(20, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);


  WebElement foo =(WebElement) wait.until(
   new Function<WebDriver, WebElement>() {
   public WebElement apply(WebDriver driver) {
   return driver.findElement(By.xpath("//input[@value='Sign up']"));
   }
   }
   );

    driver.close();
    driver.quit();
}

Above code will wait until element with xpath //input[@value='Sign up'] is found. The code will wait for 20 seconds maximum and throw exception at the end if element is not found even after 20 seconds.


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Selenium Webdriver architectural diagram

In this post, you will get to know the Selenium Webdriver architectural diagram.
Before you take a look at diagram, kindly note below points.

  1. Selenium webdriver uses JSON WIRE protocol over well known HTTP protocol.
  2. Your automation code sends HTTP commands to Webdriver Server (IEDriverServer.exe or ChromeDriver.exe).
  3.  Webdriver Server (IEDriverServer.exe or ChromeDriver.exe) sends these commands to the browser under test through HTTP proxy.
  4. Browser under test executes the commands sent by Webdriver Server and sends the results back to the Webdriver Server.
  5. Webdriver server interprets the results and your automation code takes further action on those results.



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Selenium Webdriver JSON Protocol

Did you ever wonder how Selenium 2.0 works internally?
In this post, you will get to know how selenium automates the browser.

Selenium API sends HTTP commands in the form of JSON protocol to Selenium Server.
Selenium server then uses native browser API to automate the browser.

So when use below statement in your code -
driver = new ChromeDriver();

It actually sends the below HTTP command to the selenium server.

POST /session

For each selenium API method, there is a corresponding HTTP request that is sent to the server. Here is the list of some of the HTTP commands that are sent to Selenium Server.

  1. POST /session  - Create new session
  2. GET /status - Get the state of server
  3. DELETE /session/:sessionId - Delete the session with id - sessionId
  4. POST /session/:sessionId/timeouts/implicit_wait  - Specify the amount of time the driver should wait when searching for elements.
  5. GET /session/:sessionId/url - Navigate to the specific url
Below image demonstrates how the JSON protocol works in Selenium.



More information at below links -
What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to right click and select value from context menu in Selenium webdriver

We can use Robot class to simulate clicking on the option in context menu. Below code demonstrates how we can right click to open the context menu and then select the option from menu.

@Testpublic void testRightClick() throws Exception{
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Sagar\\Videos\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("http://www.softpost.org/selenium-test-page/");
    WebElement element = driver.findElement(By.xpath("//td[contains(text(),'First Name')]//following-sibling::td//input"));
    new Actions(driver).contextClick(element).build().perform();
    pressKeyByRobot();
    Thread.sleep(5000);
    driver.close();
    driver.quit();
}

public static void pressKeyByRobot() throws Exception{
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_DOWN);
    r.keyPress(KeyEvent.VK_DOWN);
    r.keyRelease(KeyEvent.VK_ENTER);
}


Please note that above code will work only when the menu options are fixed and enabled. Above code will click on second enabled option.

Most of the times, working with context menu is simpler than what people think. After opening the context menu, you can identify the options in menu as any other normal selenium web elements and then use click method. Please note that built-in context menu can not be identified as HTML web element as it's not a part of HTML DOM But Most of the custom context menus developed by developers are a part of HTML DOM. So you can definitely go ahead and use selenium API to interact with that kind of menu.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

You are using an unsupported command-line flag: --ignore-certifcate-errors. Stability and security will suffer

When automating chrome browser using Selenium, we often get warning saying -
You are using an unsupported command-line flag: --ignore-certifcate-errors. Stability and security will suffer.









To fix this warning, you use below code while launching browser.

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--test-type");
driver = new ChromeDriver(chromeOptions);


So if we start chrome using above chrome option, that warning is not shown.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Thursday 24 March 2016

Setting up Selenium Gradle project in Intellij IDEA

Gradle is one of the most popular build management systems in the Java world. Gradle is developed to eliminate the drawbacks in Ant and Maven. In this article, you will learn how you can set up a selenium project using Gradle in Intellij IDEA.

The tools you will need are -

  1. JDK - You can know more about JDK installation process in Windows on Softpost Java Tutorial
  2. Intellij IDEA IDE - Community Edition (It's free)
  3. Gradle (It's free) In latest versions of Intellij IDEA (15.0.4+) , Gradle comes built-in So you do not need to download it separately.
Below Images will guide you through the steps for creating the Selenium-Gradle project.

Step 1 - Click on New Project menu in Intellij IDEA and then select Gradle Project


Step 2 - Types in the Group Id and Artifact Id for your project


Step 3 - Provide Gradle Settings


Step 4 - Type Project Name

Step 5 - Gradle project directory layout



Step 6 - Build.Gradle File and Selenium dependency



Step 7 - Write and execute Selenium tests


Step 8 - Executing gradle tasks


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Selenium installation set up in Intellij IDEA Maven project

Maven is one of the most popular build management systems in the Java world. In this article, you will learn how you can set up a selenium project using Maven in Intellij IDEA.

The tools you will need are -

  1. JDK - You can know more about JDK installation process in Windows on Softpost Java Tutorial
  2. Intellij IDEA IDE - Community Edition (It's free)
  3. Maven (It's free)
In latest versions of Intellij IDEA (15.0.4+) , maven comes built-in So you do not need to download it separately.

Below Images will guide you through the steps for creating the maven project.

Step 1 - Click on New Project menu in Intellij IDEA and then select Maven Project and Archetype


Step 2- Type in Group Id and Artifact Id for you project.
Step 3 - Provide the maven home directory and if you like you can also override maven settings


Step 4 - Type in the name of the project and project directory.

Step 5 - Your sample maven project will look like below.



Step 6 - Your sample POM.xml file will look like below. To use Selenium API, you will need to add Selenium dependency as shown in below image. We are using selenium version 2.53.0


Step 7 - Write sample Junit test to launch Firefox browser and execute using shortcut key Ctrl+shift+F10 or you can also right click on the code and click on Run.


Step 8 - You can also execute any maven phase like clean, validate, compile, test etc using Maven project window. 






What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Buy Best Selenium Books

Contributors