Automation Using Selenium Webdriver

Thursday, 20 October 2016

Verify Image Presence in Web Page using Selenium WebDriver


JavaScript executor is one of themost useful features of Selenium WebDriver. It allows Selenium user to perform many complex scenarioseasily. This post covers one such important scenario.Selenium verify image present example using WebDriver. We have used JavaScript executor in WebDriver Java code hereto verify if image is present in a web page.


@Test
public void CheckImage() throws Exception {
driver.get(baseUrl);
WebElement ImageFile = driver.findElement(By.xpath("//img[contains(@id,'Test Image')]"));
        
        Boolean ImagePresent = (Boolean) ((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", ImageFile);
        if (!ImagePresent)
        {
             System.out.println("Image not displayed.");
        }
        else
        {
            System.out.println("Image displayed.");
        }
}
Run your test. It should identify if image is displayed in web page and will print appropriate result in console

Page Object Model(SingIn-Page)Exp

By Using Page Object Model SignInPage  Store Locaters and Test  Best Example for (Singin-Page)

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

/**
 * Class which models the view of Sign-In page
 */
public class SignInPage {
 
    @FindBy(id="username")
    private usernameInput;

    @FindBy(id="password")
    private passwordInput;

    @FindBy(id="signin")
    private signInButton;

    private WebDriver driver;

    public SignInPage(WebDriver driver) {
        this.driver = driver;
    }
 
    /**
     * Method to perform login
     */
    public HomePage performLogin(String username, String password) {
        usernameInput.sendKeys(username);
        passwordInput.sendKeys(password);
        signInButton.click();
        wait.ForPageToLoad();
        return PageFactory.initElements(driver, HomePage.class);
    }
}


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
/**
 * Class which models the view of home page
 */
public class HomePage {
    @FindBy(id="logout")
    private logoutLink;

    private WebDriver driver;

    public HomePage(WebDriver driver) {
        this.driver = driver;
    }
 
    /**
     * Method to log out
     */
    public SignInPage logout() {
        logoutLink.click();
        wait.ForPageToLoad();
        return PageFactory.initElements(driver, SignInPage.class);
    }
}

/**
 * Login test class
 */
public class LoginTest {
    public void testLogin() {
        SignInPage signInPage = new SignInPage(driver);
        HomePage homePage = signInPage.login(username, password);
        signInPage = homePage.logout();
    }
}

Challenges faced while working on Selenium

Challenges faced while working on Selenium

There are many challenges we face while working on selenium. Some of the challenges are:

Challenges faced that are as follows:
·         Frequently changing UI. It always need to make changes in code most of the time.
·         Stuck somewhere while running automation scripts in chrome browser getting error that element is not visible, element not found.
·         New kind of element like ck-editor, bootstrap calendar and dynamic web tables. But get the solution always.
·         Reused of test scripts.
·         To be continued

1. configuration challenges on different machines
2. selenium's compatibility with browser versions like with FF20 is not supported with some web-driverversions.
3. handling IE/chrome etc.
4. popup handling
5. Ajax handling
6. security certificate handling
7. iframes
8. date pick from calender.
9. identifying locators
10. Upload and download file
11. Maintain the scripts to work properly irrespective of new build
12. Diff to identify script has failed may be unable to locate the element
or config issue(Browser updated) if your framework is not able to catch issue.
13. If you are using xpath as a locator. writing xpath without using dynamic changing data.
i.e., xpath generated dynamically.

Enter a text without using SendKeys method() in Selenium Webdriver

How to Send text without using sendkeys methods

public class type{

public static void setattribute(WebElement element,String attributename,String Value){

WrapsDriver wrappedElement=(WrapsDriver)element;
JavascriptExecuter driver =(JavaScriptExecutor)wrappedElement.getWrapedDriver;
driver.executeScript(arguments[0].setAttribute(arguments[1],arguments[2]",element,
                                    attributeName,value);
}

//or

JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('email').value = 'thotajagan@gmail.com';");


Onemore Example:

driver.get("http://facebook.com/");
WebElement cssValue= driver.findElement(By.xpath(".//*[@id='s']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('s').value='Virender Testing   
sending'");

Wednesday, 19 October 2016

PageObject Facebook test Real time Scenario Example

****************************************************************
    ***            Facebook MainPageObject Start                                      ****
_________________________________________________________________
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class FacebookMainPageObject extends WikiBasePageObject {

  @FindBy(css = "#email")
  private WebElement emailField;
  @FindBy(css = "#pass")
  private WebElement passwordField;
  @FindBy(css = "#loginbutton")
  private WebElement loginButton;

  public FacebookMainPageObject(WebDriver driver) {
    super();
  }

  public FacebookUserPageObject login(String facebookEmail, String facebookPassword) {
    typeEmail(facebookEmail);
    typePassword(facebookPassword);
    clickLoginButton();
    return new FacebookUserPageObject(driver);
  }

  public void clickLoginButton() {
    wait.forElementVisible(loginButton);
    loginButton.click();
    PageObjectLogging.log("clickLoginButton", "facebook login button clicked", true);
  }

  private void typePassword(String password) {
    wait.forElementVisible(passwordField);
    passwordField.sendKeys(password);
  }

  private void typeEmail(String email) {
    wait.forElementVisible(emailField);
    emailField.sendKeys(email);
  }
}
*****************************************************************************
   *                                   FacebookSettingsPageObject.java                                          *
_____________________________________________________________________________


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import java.util.List;

public class FacebookSettingsPageObject extends WikiBasePageObject {

  @FindBy(css = "#pageLogo")
  private WebElement pageLogo;
  @FindBy(css = "#pop_content .uiButtonConfirm")
  private WebElement removeButton;
  @FindBy(css = ".pop_container_advanced")
  private WebElement removeAppConfirmationModal;
  @FindBy(css = "._4bl7")
  private List<WebElement> pageElementList;
  @FindBy(css = "#userNavigationLabel")
  private WebElement fbDropDown;
  @FindBy(xpath = "//span[text()='Log Out']")
  private WebElement fbLogOut;

  public FacebookSettingsPageObject(WebDriver driver) {
    super();
  }

  public FacebookSettingsPageObject open() {
    getUrl(URLsContent.FACEBOOK_SETTINGS_APP_TAB);

    return this;
  }

  public void verifyPageLogo() {
    wait.forElementVisible(pageLogo);
    PageObjectLogging.log("verifyPageLogo", "Page logo is present", true);
  }

  /**
   * from facebook Apps.
   */
  public FacebookSettingsPageObject removeAppIfPresent() {
    if (isAppPresent()) {
      for (WebElement element : pageElementList) {
        if (element.getText().toString().matches("^Wikia.*\n?.*")) {
          wait.forElementVisible(element);
          element.click();
          WebElement AppRemoveButton =
              element.findElement(By.xpath("//a[contains(text(), 'Remove')]"));
          if (AppRemoveButton != null) {
            wait.forElementVisible(AppRemoveButton);
            AppRemoveButton.click();
            wait.forElementVisible(removeButton);
            removeButton.click();
            waitForElementNotVisibleByElement(removeAppConfirmationModal);
            driver.navigate().refresh();
            try {
              Thread.sleep(3000);
            } catch (InterruptedException e) {
              PageObjectLogging.log("SLEEP INTERRUPTED", e, false);
            }

            PageObjectLogging.log("removeApp", "Wikia App removed", true);
          }
        } else {
          PageObjectLogging.log("removeApp", "Wikia App not found", true);
        }
      }
    }
    return this;
  }

  /**
   * This method verifies if App is present on facebook apps list. It searches  string.
   */
  private boolean isAppPresent() {
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      PageObjectLogging.log("isAppPresent", e, false);
    }
    boolean isPresent = false;
    for (WebElement element : pageElementList) {
      if (element.getText().toString().matches("^Wikia.*\n?.*")) {
        isPresent = true;
      }
    }
    return isPresent;
  }

  public void logOutFB() {
    wait.forElementVisible(fbDropDown);
    fbDropDown.click();
    wait.forElementVisible(fbLogOut);
    fbLogOut.click();
  }
}

**************************************************************
  *                       Facebook User PageObject                                        *
______________________________________________________________

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

public class FacebookUserPageObject extends WikiBasePageObject {

  @FindBy(css = "a[href$='?ref=logo']")
  private WebElement pageLogo;

  public FacebookUserPageObject(WebDriver driver) {
    super();
  }

  public void verifyPageLogo() {
    wait.forElementVisible(pageLogo);
    PageObjectLogging.log("verifyPageLogo", "Page logo is present", true);
  }

  public FacebookSettingsPageObject fbOpenSettings() {
    getUrl(URLsContent.FACEBOOK_SETTINGSPAGE);
    return new FacebookSettingsPageObject(driver);
  }
}
**********************************************************************************
                     PageObject for facebook   Ends
______________________________________________________________________________*____

how to delete default values in text field using selenium

Selenium WebDriver:  overwrite value in field instead of appending to it with sendKeys using Java

Use this Code:

element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");


how to delete default values in text field using selenium:
Use this Code

WebElement toClear = driver.findElement("locator");
toClear.sendKeys(Keys.CONTROL + "a");
toClear.sendKeys(Keys.DELETE);

Selenium: delete contents from a textbox


The keyPress event of selenium can be helpful:

selenium.sendKeys("text1", "ABCD");
selenium.sendKeys("text1", "\b");
selenium.sendKeys("text1", "\b");

This will Click Backspace key twice

Significance of Maven,Svn,Jenkins in selenium webdriver

Significance of Maven,Svn,Jenkins in selenium webdriver?

Most Important in Selenium webdriver this topics and uses


The tools you name are used during different steps in the SDLC, they can be replaced by other
alternative tools

Example (partial) development life cycle:
Programming -> Check-in to version control -> Schedule build and run build -> Run automated test --->against build -> Report failing tests/buildsCheck-in to version control

After developers are finished with development they Check-In the code into a version controlsystem,
this to keep a history of all the changes. SVNs relation to Selenium testing is that you want to test against the latest version of the application. Also its advisable to keep the test-code close to the
application code and I would version it in the same repository.

Schedule build and run build

The build-server / continuous integration server monitors the version control, checks out any changes
and schedules a build against this version. Relation to Selenium testing is that Jenkins can prepare
the application and set it up in such a state that you can run the tests against it. Its possible to
use Maven as a tool to automate the building,integrating and or setup of the application instead of
using shell scripts.

Run automated test against build

After the build is OK, the build-server checks out and starts the Selenium tests. Maven can be used to
 build and start tool that is fired by Jenkins to trigger the test start

Report failing tests/builds

The build-server reports any failing tests in its main overview or sends out e-mail to the person who
broke or monitors the build.

Alternative tools:

Build-tools
Build-servers
Version control systems