Automation Using Selenium Webdriver

Monday 17 October 2016

How to compare values from the list or from dropdown list in webdriver (Java)

Currently working on Selenium WebDriver and using Java for scripting.
I have stored all drop down values of db in property file and want to compare same values whether they are in UI as in DropDown options.
The visualization.txt which is in C: directory contains the below options visualizationId=Month
So How can I compare both values are matching. I need to get all the drop down options from property file i.e visualization.txt then need to check in the drop drop down in UI

public class Ex1 {
private WebDriver d;
@Test
public void testUntitled() throws Exception {
d = new FirefoxDriver();
d.get("http://register.rediff.com/commonreg/index.php?redr=http://portfolio.rediff.com/money/jsp/loginnew.jsp?redr=home");

String[] exp = {"Month", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
WebElement dropdown = d.findElement(By.id("date_mon"));
        Select select = new Select(dropdown);

        List<WebElement> options = select.getOptions();
        for(WebElement we:options)
        {
         for (int i=0; i<exp.length; i++){
             if (we.getText().equals(exp[i])){
             System.out.println("Matched");
             }
           }
         }  }}


OUTPUT:
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched
Mateched

IEDriver - How To Resolve Set IE browser Zoom Level To 100% Error On RunTime

IEDriver - How To Resolve Set IE browser Zoom Level To 100% Error On RunTime
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class IESetZoom {
 public static void main(String[] args) throws Exception {

  // Set path of IEDriverServer.exe
  // Note : IEDriverServer.exe should be In D: drive.
  System.setProperty("webdriver.ie.driver", "D://IEDriverServer.exe");

  // Set desired capabilities to Ignore IEDriver zoom level settings and disable native events.
  DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
  caps.setCapability("EnableNativeEvents", false);
  caps.setCapability("ignoreZoomSetting", true);

  // Initialize InternetExplorerDriver Instance using new capability.
  WebDriver driver = new InternetExplorerDriver(caps);
  driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

  // Press CTRL + 0 keys of keyboard to set IEDriver Instance zoom level to 100%.
  driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0"));

  // Load sample calc test URL
  driver.get("http://www.corejavawithselenium.blogspot.in");

  // Execute sample calc test.
  driver.findElement(By.xpath("//input[@id='1']")).click();
  driver.findElement(By.xpath("//input[@id='plus']")).click();
  driver.findElement(By.xpath("//input[@id='6']")).click();
  driver.findElement(By.xpath("//input[@id='equals']")).click();
  String result = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
  Thread.sleep(5000);
  System.out.println("Calc test result Is : " + result);
  driver.close();
 }
}

TestNG Selenium Simple Search Example

 TestNG Selenium Simple Search Example::
Selenium provides WebDriver as its API for automating web application testing. WebDriver drives the browser directly using each browser’s built-in support for automation.
In this example, we will use the WebDriver to open google and search for TestNG.
WebDriver is an interface so we still need to an implementation to run the test on an actual browser.
We will select the implementation based on the browser used. For example, if we are using firefox,
we will use FirefoxDriver. If it is chrome, we will use ChromeDriver. Since ChromeDriver works with Chrome through the chromedriver.exe, we need to make sure that the binary be placed somewhere on yoursystem’s path.
Points to be noted regarding the test class:
In @BeforeSuite method, initDriver(), we create the driver.
searchTestNGInGoogle() is our test method.
We call driver.navigate().to(url) to open the url.
Once the site is open, we need to get a handle on the search field so that we can type in the text to
 be searched.
When we call driver.findElement(By.name("q")), the WebDriver locates the search field using matching name attribute.
Next, we call element.sendKeys("TestNG") to type in the text “TestNG” in the search field.
The search is submitted on calling element.submit().
Finally, we wait for the results to be returned.
In @AfterSuite method, quitDriver(), we call driver.quit() to close the browser session.

TestNGSeleniumSimpleSearchExample:


package com.javacodegeeks.testng.selenium;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.ExpectedCondition;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.annotations.AfterSuite;

import org.testng.annotations.BeforeSuite;

import org.testng.annotations.Test;

public class TestNGSeleniumSimpleSearchExample {

    private WebDriver driver;



    @BeforeSuite

    public void initDriver() throws Exception {

        System.out.println("You are testing in firefox");

        driver = new FirefoxDriver();

    }



    @Test

    public void searchTestNGInGoogle() {

        final String searchKey = "TestNG";

        System.out.println("Search " + searchKey + " in google");

        driver.navigate().to("http://www.google.com");

        WebElement element = driver.findElement(By.name("q"));

        System.out.println("Enter " + searchKey);

        element.sendKeys(searchKey);

        System.out.println("submit");

        element.submit();

        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {

            public Boolean apply(WebDriver d) {

                return d.getTitle().toLowerCase()

                        .startsWith(searchKey.toLowerCase());

            }

        });
        System.out.println("Got " + searchKey + " results");

    }



    @AfterSuite

    public void quitDriver() throws Exception {

        driver.quit();

    }

[TestNG] Running:

  OUTPUT:



You are testing in firefox
Search TestNG in google
Enter TestNG
submit
Got TestNG results



==============================================

TestNgSeleniumSuite

Total tests run: 1, Failures: 0, Skips: 0

===============================================

Sing in-Sing out of Facebook using selenium WebDriver


Sign in- Sign out facebook Example using selenium webdriver
public class facebook
{
public static void main(String[] args) throws InterruptedException {

WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.facebook.com");
System.out.println("Title of the page "+ driver.getTitle());
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("xxxxx@gmail.com");
WebElement password = driver.findElement(By.id("pass"));
password.sendKeys("xxxxx");
WebElement Signup_button = driver.findElement(By.id("loginbutton"));
Signup_button.click();
Thread.sleep(5000);
System.out.println("After login title is = " + driver.getTitle());
WebElement logOut = driver.findElement(By.id("userNavigationLabel"));
logOut.click();
Thread.sleep(5000);
WebElement signOut = driver.findElement(By.name("Log Out"));
logOut.click();

System.out.println("Logged Out Successfully!!!!!!!!!!!!!!!!!!!");
String pagetitle = driver.getTitle();
System.out.println(pagetitle);

}}

Linkedin Login-Logout Using Selenium webdrier


Linkedin Sign in-Sign out Example Using Selenium Webdriver

   public class LinkedIn
 {
    WebDriver driver = new FirefoxDriver();
    @BeforeTest
    public void setUp() throws Exception {

        String baseUrl = "http://www.linkedin.com/";  
        driver.get(baseUrl);

    }


    @Test
    public void login() throws InterruptedException
    {
        WebElement login = driver.findElement(By.id("login-email"));
        login.sendKeys("*****@gmail.com");

        WebElement pwd = driver.findElement(By.id("login-password"));
        pwd.sendKeys("*****");


        WebElement in = driver.findElement(By.name("submit"));
        in.click();

        Thread.sleep(10000);
    }


     @Test
        public void profile()  {
    // here it gives error to me : Unable to locate element
        Thread.sleep(5000);
        Actions action = new Actions(driver);
        WebElement profile = driver.findElement(By.xpath("//*[@id='img-defer-id-1-25469']"));
        action.moveToElement(profile).build().perform();
        driver.quit();
    }


}

Sunday 16 October 2016

Fieldlevel validation in Selenium Webdriver (Java)

 Check Filedlevel Validation in Selenium Webdriver(Java)

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Validations {
public static WebDriver d;
    public static void main(String []args)throws Exception{
        d = new FirefoxDriver();
        d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        d.get("http://www.vrlbus.in/vrl2013/register_customer.aspx");
        d.findElement(By.id("FIRSTNAME")).sendKeys("#!#!#$@#!$@!$@#$%#%^#$^^&%&$%*");
        d.findElement(By.id("Button1")).click();
        String alertMessage = d.switchTo().alert().getText();
        System.out.println(alertMessage);
      if (alertMessage.equals("First name Should not contain Special Characters")){
            System.out.println("Error displayed: First name Should not contain Special Characters");
            d.switchTo().alert().dismiss();
        } else{
            System.out.println("Accepted");
        }
        d.findElement(By.id("FIRSTNAME")).sendKeys("acbcdefghijklmnopqrstuvwxyzabcdef");
        d.findElement(By.id("Button1")).click();
         if (alertMessage.equals("First name Should not contain Special Characters")){
                System.out.println("Error displayed: First name Should not contain Special Characters");
                d.switchTo().alert().dismiss();
            } else{
                System.out.println("Accepted");
            }
        d.quit();
    }  
}


Second example


public static void main(String[] args) throws Exception {
    String[] invalidChars = {"#", "!", "$", "@", "%", "^", "&"};
    String name = "acbcdefghijklmnopqrstuvwxyzab";
    d = new FirefoxDriver();
    d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    d.get("http://www.vrlbus.in/vrl2013/register_customer.aspx");
    for (String invalid : invalidChars) {
        d.findElement(By.id("FIRSTNAME")).clear();
        d.findElement(By.id("FIRSTNAME")).sendKeys(name + invalid);
        d.findElement(By.id("Button1")).click();
        String alertMessage = d.switchTo().alert().getText();
        System.out.println(invalid);
        if (alertMessage.equals("First name Should not contain Special Characters")) {
            System.out.println("Error displayed: First name Should not contain Special Characters");
            d.switchTo().alert().dismiss();
        } else {
            System.out.println("Accepted");
        }
    }
    d.findElement(By.id("FIRSTNAME")).sendKeys("acbcdefghijklmnopqrstuvwxyzabcdef");
    d.findElement(By.id("Button1")).click();
    String alertMessage = d.switchTo().alert().getText();
    if (alertMessage.equals("First name Should not contain Special Characters")) {
        System.out.println("Error displayed: First name Should not contain Special Characters");
        d.switchTo().alert().dismiss();
    } else {
        System.out.println("Accepted");
    }
    d.quit();
}

General Function To Comparing Two Strings In Selenium WebDriver TestCase

General Function To Comparing Two Strings In Selenium WebDriver TestCase

When you will use selenium webdriver to automate real worldapplications, Many times you have to compare two strings like page title, product name or any other string. And based on comparison result you have to take specific action. Simple example of such scenario Is, You are navigating on any view product page to add product In to basket. But before adding product In basket, You wants to verify product's name to check It Is correct product or not


Many time you have to compare strings In automating any single application. So What you will do? You will write samecode multiple time In your different scripts? General 
way(Which I am using) Is to create common method In baseclass (Which Is accessible from all test classes) to compare two strings. Then we can call that method by passing actualand expected string to compare strings whenever required In out tests.

Let me explain you how to do It.

Step 1 : Create CommonFunctions Class In your package which can be accessible by any other class.
Step 2 : Create method compareStrings which can accept twostring values. Also Create object of TestNG SoftAssert class to assert assertion softly as shown In bellow given 
example.
package Testng_Pack;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class CommonFunctions {

 SoftAssert Soft_Assert = new SoftAssert();

 public boolean compareStrings(String actualStr, String expectedStr){
  try{
   //If this assertion will fail, It will throw exception and catch block will be executed.
   Assert.assertEquals(actualStr, expectedStr);
   }catch(Throwable t){
    //This will throw soft assertion to keep continue your execution even assertion failure.
    //Use here hard assertion "Assert.fail("Failure Message String")"
 If you wants to stop your test on assertion failure.
    Soft_Assert.fail("Actual String '"+actualStr+"' And Expected String '"+expectedStr +"' Do Not Match.");
    //If Strings will not match, return false.
    return false;
   }
  //If Strings match, return true.
  return true;
 } 
}