Saturday, January 3, 2015

Highlight WebElements using Selenium WebDriver





Highlight WebElements feature is not available for Selenium Webdriver.

In Selenium there is no any Native movements hence its very hard for a selenium user to recognize where the selenium clicks or to know currently on which elements its being executed.

There is no any direct API available in WebDriver to perform this operation,But, we can achieve this using the JavaScript Executor.

Below code will achieve highlighting elements during WebDriver execution

In This Program

  1. Navigating to http://www.automationplace.blogspot.com
  2.  highlight " View my profile link"
  3.  highlight " Prashanth kk" link and click on that.


Step 1:

First we need to create a separate class file.which will hold the highlighting function.

New - > Class -> highlightclass

Source Code for highlightclass.java

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class highlightclass {
      
       public void highlightElement(WebDriver driver, WebElement element) throws InterruptedException {

         
              JavascriptExecutor js=(JavascriptExecutor)driver;
                     for (int i = 0; i < 3; i++) {
                           js.executeScript("arguments[0].setAttribute('style', arguments[1]);",

                           element, "color: green; border: 5px solid green;");
                           Thread.sleep(2000);
                           js.executeScript("arguments[0].setAttribute('style', arguments[1]);",

                           element, "");

                     }
       }


}

In the above example am using JavascriptExecutor and highliting the element in green color 
color: green; border: 5px solid green;

Step 2 :

Create another class to Write automation Script and call highlightElement function

New - > Class -> funtionclass

funtionclass.java

Source Code :

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class functionclass {

       public static void main(String[] args) throws InterruptedException {
              // TODO Auto-generated method stub
             
              //Create object for Class method
           method method=new method();
              WebDriver driver=new FirefoxDriver();
              driver.get("http://www.automationplace.blogspot.com");
              WebElement element=driver.findElement(By.xpath("//*[@id='Profile1']/div/a[2]"));
              method.highlightElement(driver, element);
              WebElement aboutlink=driver.findElement(By.xpath("//*[@id='Profile1']/div/dl/dt/a"));
              method.highlightElement(driver, aboutlink);
              aboutlink.click();
              driver.quit();

       }
      

}

Here am highlighting two webelements using highlightclass function

1. Highlight " View my profile link"




2. Highlight " Prashanth kk" link and click on that.




Hope you Like this post.







Friday, January 2, 2015

Get URL,Title and Particular Text from Site using Selenium Webdriver



Hi Guys in this article we are going to discuss about how to get the following things


  • URL
  • Page Title 
  • Particular Text from Site

 from webSite using Selenium Web driver.

This can be easily achieved using selenium inbuild Methods :


  • getTitle();
  • getText();
  • getCurrentUrl();

In this Program :
  1. Navigating to http://www.automationplace.blogspot.com.
  2. Getting page Title using                                      
  
    String title = driver.getTitle();

   System.out.println("Current Title for the Page is : " + title);

   3.Getting page Text using



 WebElement pagetext=driver.findElement(By.xpath("//[@id='headerinner']/div[2]/p/span"));
String text=pagetext.getText();
System.out.println("Text From Page "+text);

   4 .Clicking on about link and Getting Current Page URL using



       driver.findElement(By.xpath("//*[@id='Profile1']/div/dl/dt/a")).click();
    Thread.sleep(7000);
    String currentpageurl = driver.getCurrentUrl();
    System.out.println("Current Page URL is :"+currentpageurl);



Source Code :

package gettext;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class textinfo {

       public static void main(String[] args) throws InterruptedException {
              // TODO Auto-generated method stub
                WebDriver driver = new FirefoxDriver();
                driver.manage().window().maximize();
                driver.navigate().to("http://www.automationplace.blogspot.com");
                String title = driver.getTitle();
                System.out.println("Current Title for the Page is : " + title);
                Thread.sleep(5000);
                WebElement pagetext=driver.findElement(By.xpath("//*[@id='header-inner']/div[2]/p/span"));
                String text=pagetext.getText();
                System.out.println("Text From Page "+text);
                driver.findElement(By.xpath("//*[@id='Profile1']/div/dl/dt/a")).click();
                Thread.sleep(7000);
                String currentpageurl = driver.getCurrentUrl();
                System.out.println("Current Page URL is :"+currentpageurl);

       }

}


Run the above program.your output looks like below.





Hope you like this post.

Thank you.



Thursday, January 1, 2015

Listners in Testng Framework



  1.  @listner is a testNG annotation

·         This is one very important annotation if you chose to have some default behavior for your test case when it failspasses and skip etc.

·         2. You can either extend 'TestListenerAdapter' or implement Interface 'ITestListener' which is a listener for test running.

              Eg : if you extend TestListenerAdapter class and write your implementation in a custom listner  to override onTestFailure or onTestSuccess methods you will be able to do  anything which you want when a test fails or passes, like taking screenshots,printing logs etc.

i.e)  Suppose your test case is passed and you want to write something in console at that case just you need to override a method onTestSuccess(ITestResult tr)
      Suppose your test case is failed and you want to take screenshot at that case just you need to override a method onTestFailure(ITestResult tr)

Methods available in TestListnerAdapter

·       1.  OnTestSuccess : Invoked each time a test succeeds.
·       2.  OnTestFailure : Invoked each time a test fails
We can implement any logic that you want to do when a test fails, Normally most of them prefer 
taking screen shots when a test fails. Here in this method we can add a logic to take the screen shot and the name of the test as screenshot name.
·         OnTestSkipped : Invoked each time a test is skipped.



In this program :
  1. Navigating to gmail
      driver.get("http://www.gmail.com"); 

   2. Verifying the Heading 

   Assert.assertEquals(Heading, "One account. All of Google.");

   3. Failing the testcase because there is no signin webelement

     driver.findElement(By.name("signin")).click();



In listnerclass.java:

   1. For Passed test am just printing like "Test Passed" in console

   public void onTestSuccess(ITestResult tr)  {
               
                System.out.println("TestPassed");
               }
      
   2 . For Failed Test am taking Screenshot and store it in (D:\\failure.png) drive


      public void onTestFailure(ITestResult itr)
       {
             
             
              File scrFile = ((TakesScreenshot)Properties.driver).getScreenshotAs(OutputType.FILE);
              // Now you can do whatever you need to do with it, for example copy somewhere
              try {
                     FileUtils.copyFile(scrFilenew File("D:\\failure.png"));
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Taken screenshot because testcase failed");
             
       }

    
   

Lets see the above things in action.

      



·         1. Create a new package name it as listener.


2. Create a new class properties.java


This is used to intialize the Webdriver.

Source code for properties.java

package listner;

import org.openqa.selenium.WebDriver;

public class Properties {
      
       public static WebDriver driver;

}






 Create a simple class named as Listner and extends TestListenerAdapter



3 . extends TestListenerAdapter




After extends TestListenerAdapter am going to override some methods.
*  onTestSuccess(ITestResult tr)
*  onTestFailure(ITestResult itr)

Source code for MyListner.java

package listner;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;


public class MyListner extends TestListenerAdapter{
      
      
      
       public void onTestSuccess(ITestResult tr)  {
               
                System.out.println("TestPassed");
               }
      
       //Am going to take screenshot on failure
       public void onTestFailure(ITestResult itr)
       {
             
             
              File scrFile = ((TakesScreenshot)Properties.driver).getScreenshotAs(OutputType.FILE);
              // Now you can do whatever you need to do with it, for example copy somewhere
              try {
                     FileUtils.copyFile(scrFilenew File("D:\\failure.png"));
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Taken screenshot because testcase failed");
             
       }

}


Make a new class named as Logintest in which your testcases are running and  write the @Testng annotations and create two Testcases in this class

 4. Create a new Class name it us Logintest





Source code for logintest.java

package listner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;


public class Logintest extends Properties{
      
       public WebDriver driver;
       public Logintest()
       {
              Properties.driver = new FirefoxDriver();
              driver = Properties.driver;
       }
      
       @Test(priority=0)
       public void verifytextsucess()
       {
              driver.get("http://www.gmail.com");
              //Verify the heading is correct
              WebElement text=driver.findElement(By.xpath("html/body/div[1]/div[2]/div[1]/h1"));
              String Heading=text.getText();
              System.out.println(Heading);
              Assert.assertEquals(Heading"One account. All of Google.");
       }
      
       @Test(priority=1)
       public void loginfail()
       {
              //This test will fail because there is no signin webelement
              driver.get("http://www.gmail.com");
              driver.findElement(By.name("Email")).sendKeys("kk.prashanth65@gmail.com");
           driver.findElement(By.name("Passwd")).sendKeys("smartboys");
           //signin webelement is not present
           driver.findElement(By.name("signin")).click();
          
       }
      
       @AfterTest
       public void endtest()
       {
              driver.quit();
       }
}


5.  The below is the Test.xml file.

In the above Test.xml file, We need to pass the class name where we have the test methods. And also we should define listeners in testng.xml file so that TestNG can use them to rewrite the annotations.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Test Suite">
  <listeners>
    <listener class-name="listner.MyListner" />
  </listeners>
<test name="Logintest">
    <classes>
        <class name="listner.Logintest" ></class> 
    </classes>
</test>
</suite>



Now right click in Test.xml - > RunAs -> TestNG Suit






Once you run. your Test output look like below.


It will also take the screenshot once its complete the Test


The screenshot looks like above..Because the Webelement button name is incorrect in Test.




Hope you Like this post.

Hit LIKE Button on facebook page to stay connected.

Thanks.