Earn Money in 10 days

Selenium Videos

Protractor In Selenium

Livechat

Wednesday, 25 February 2015

How to send a attachment via gmail using Selenium(Using Robot Class)

Scenario:

Open gmail.com
Enter username 
Enter Password
Click on SignIn
Click on composeButton
Add recipent
Add Subject
Click on attachment
Add your File location
Click on Send Button


import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class SendFile {
public static void main(String str[]) throws InterruptedException, AWTException{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.gmail.com/");
//open gmail
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("enteryouremailid");
//enter emailid
driver.findElement(By.xpath(".//*[@id='Passwd']")).sendKeys("enteryourpassword");
   // enter password
driver.findElement(By.xpath("//*[@id='signIn']")).click();
//click on sign in
driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
//click on compose button

driver.findElement(By.xpath("//form[1]//textarea[1]")).sendKeys("ritu7181@gmail.com");
//enter email id where you need to send email

driver.findElement(By.xpath("//div[@class='aoD az6']//input[@class='aoT']")).sendKeys("Please find attachment");
//Enter subject
     Thread.sleep(15000);
driver.findElement(By.xpath("//div[@class='a1 aaA aMZ']")).click();
//click on attachment icon
StringSelection ss = new StringSelection("C:\\Users\\Ritika Gulati\\Downloads\\Asp.docx");
    //upload your file using RobotClass
    //attach your path where file is located.
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    Robot robot = new Robot();
    Thread.sleep(5000);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyRelease(KeyEvent.VK_V);
    Thread.sleep(6000);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    Thread.sleep(10000);
      driver.findElement(By.xpath("//div[text()='Send']")).click();
    //Click on send
   }
}

Wednesday, 7 January 2015

What is Maven

If we have to test any web application using  Selenium everytime we need to download jar files from http://docs.seleniumhq.org/download/ and configure into eclipse.If we need test reports or any jar files we first download and add into in our Project.But maven has solved this problem for us By using Maven we just have to add dependecies in Pom.xml files and it will downloaded all the Jar files from Server.
What is Maven
Maven – a build automation tool which is distributed under Apache Software Foundation.
What is pom.xml file.
Its the core of maven.If we need any jar files in our projects we just need to add dependencies of those jar files in Pom.xml.When maven runs it will download all the jar files from apache server.
For reference you can use this http://docs.seleniumhq.org/download/maven.jsp
If you need any jar file like poi jar or Selenium jar files  files you just need to add dependencies in POM.XML File.It will download all the jars from server.


This is pom.xml File.If you will use Maven You will get this in your project.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com..framework.datadriven</groupId>

  <artifactId>DemoProject</artifactId>
  <version>1</version>
  <packaging>jar</packaging>

  <name>Datadrivenframework</name>

  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties> 
   <dependencies>
          <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.1.1</version>
           <scope>test</scope>
          </dependency>
         <!-- Selenium -->
       <dependency>
                  <groupId>org.seleniumhq.selenium</groupId>
                  <artifactId>selenium-java</artifactId>
                  <version>2.42.2</version>
            </dependency>
         <!-- POI -->
         <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.6</version>
         </dependency>
         <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.6</version>
         </dependency>
        <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.6</version>
        </dependency>
        <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.1</version>
      </dependency>
      
      <dependency>
      <groupId>org.apache.xmlbeans</groupId>
      <artifactId>xmlbeans</artifactId>
      <version>2.3.0</version>
      </dependency>
      <!--  Log4J  -->
      <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      </dependency>
      <!-- JavaMail  -->
      <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4</version>
      </dependency>  
        </dependencies>
          <build>
      <plugins>
                  <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-surefire-plugin</artifactId>
              <configuration>
                <!--  suiteXmlFiles>
       <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>    
                </suiteXmlFiles-->
              </configuration>
            </plugin>        
    </plugins>
      </build>
    <reporting>
        <plugins>
        <!-- TestNG-xslt related configuration. -->
          <plugin>
            <groupId>org.reportyng</groupId>
            <artifactId>reporty-ng</artifactId>
            <version>1.2</version>
            <configuration>
              <!-- Output directory for the testng xslt report -->
              <outputdir>/target/testng-xslt-report</outputdir>
              <sorttestcaselinks>true</sorttestcaselinks>
              <testdetailsfilter>FAIL,SKIP,PASS,CONF,BY_CLASS</testdetailsfilter>
              <showruntimetotals>true</showruntimetotals>
            </configuration>
          </plugin>
        </plugins>
      </reporting>
</project>
This pom.xml will download automatically when maven 


How to download Maven

Go to this link
Step1:
You will Get a Zip folder.Extract this Zip file into Your suitable Drive.
Note:This configuration is very simple as you have configure java and ant into Your System.
Step2:
After extracting you will get this folder.

Step3:Set up maven in Environment.Go to Environment Variable.


Step4: Click on Environment Variables.

Step5: Click on New


Step6:  In variablename Textbox: Write M2_HOME.
           In variable Value Give the path of Your Apache maven upto Bin Folder.





Step7:Go to Path in System Variable.Click on Edit

Step8:Set maven path as Write ;%M2_HOME%\bin 


Step9:Open cmd prompt.
Step10: Type in cmd Prompt --version and Press enter.

Step11: Output.Maven is Installed Successfully.

How to work with Maven will Tell You in The Next Post.

Sunday, 4 January 2015

How to run your Script on Multiple Browsers In Selenium

Now a Days  it has now become crucial to test web applications on multiple browsers. On different browsers, client components like Javascript, AJAX requests, Applets, Flash, Flex etc.applications on multiple browsers. Also for different browsers you may have different handling on how requests are processed on server side based on the user-agent received from client browser. So just testing your web application on single web browser is not enough. You need to make sure that your web application works fine across multiple browser.So here I will tell you how to test a web application using selenium on multiple Browser.

Four simple steps you need to follow:

Step 1: Create your Script. Using TestNG annotations. Define parameters (using @Parameters) for taking input value i.e, which browser should be used for Running the Test

Step 2: Create a TestNG XML for running your script

Step 3: Configure the TestNG XML for passing parameters i.e, to tell which browser should be used for Running the Test

Step 4: Run the TestNG XML which can pass the appropriate browser name to the Script such that the Test Case is executed in a specified browser

Parallel Test in Selenium

Create a TestNG XML for running your test. Configure the TestNG XML for passing parameters 
This is the Testng.xml.By this you can test you application on multiple browser mention in testng.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Myparalleltest" verbose="1" parallel="tests" thread-count="2">
<test name="chrometest">
<parameter name = "browser" value ="chrome"/>
    <classes>
        <class name="paralleltest.CrossBrowsertest"></class>  cop
    </classes>
</test>
<test name="firefoxtest">
<parameter name = "browser" value ="firefox"/>
    <classes>
        <class name="paralleltest.CrossBrowsertest"></class>  
    </classes>
</test>
<test name="internetexplorertest">
<parameter name = "browser" value ="ie"/>
    <classes>
        <class name="paralleltest.CrossBrowsertest"></class>  
    </classes>
</test>
</suite>

//You need to add a annotation in you java class.By using @Parameters("browser") you can run your test on multiple browser.
Create a ‘New Class’ file and refer the name to the actual page from the test object, by right click on the above created Package and select New > Class. In our case it as CrossBrowsertest
package paralleltest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class CrossBrowsertest {
WebDriver driver;
@Parameters("browser")
@BeforeTest
public void openBrowser(String browser){
if(browser.equals("chrome")){
//If browser is equal to chrome
System.setProperty("webdriver.chrome.driver","C:\\Users\\Hp\\Desktop\\Chromepth\\ChromeDriver.exe");
      driver =  new ChromeDriver();
}else if(browser.equals("firefox")){
//If browser is equal to firefox
driver = new FirefoxDriver();  
}
else if(browser.equals("ie")){
//If browser is equal to ie System.setProperty("webdriver.ie.driver","C:\\Users\\Hp\\Desktop\\ie32bit\\IEDriverServer.exe");
           driver = new InternetExplorerDriver();
           driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}}
@Test
   public void doLogin() throws InterruptedException{
       driver.get("http://gmail.com");
       //Open url
       driver.findElement(By.id("Email")).sendKeys("selemiumgyan");
       //Enter email id
       driver.findElement(By.id("Passwd")).sendKeys("password");
    //   Enter password
   }}

Monday, 22 December 2014

How to test menus/Submenus using action class(Mouse hovering in Webdriver)

Many of the times we need to test Menus and Submenus in Selenium.
Selenium WebDriver has Advanced User Interactions API (Actions class) to perform this kind of advanced user interactions for rich applications.We can use Actions class and It different methods like moveToElement, dragAndDrop, clickAndHold.These all actions are called Mouse Hover action in Selenium Webdriver.
So Where to use these mouse hovering action.

Whenever you are Testing Menus/Submenus of a Website and you find some hidden elements/getting exception like Element is not currently visible and so may not be interacted with
At that time you need to perform mouse hovering
How to find that Webelement is Hidden.By this link you can find out element is hidden o not.
How to do Mouse Hover in SeleniumWebDriver
import java.util.concurrent.TimeUnit;
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.interactions.Actions;
public class TestingSubmenu {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.neogenomics.com/solutions-overview.htm");
    Boolean submenu =     driver.findElement(By.xpath("//*[@id='ctl00_Header1_HorizontalNavigation1_Menu_m0_m2']/span")).isDisplayed();
       System.out.println(submenu);
//If this method returns true then it is visible element and if returns False then it is hidden element.
     WebElement Menu = driver.findElement(By.xpath("//*[@id='ctl00_Header1_HorizontalNavigation1_Menu_m0']/img"));
       WebElement Submenu = driver.findElement(By.xpath("//*[@id='ctl00_Header1_HorizontalNavigation1_Menu_m0_m2']/span"));      
       if(submenu==false){
      //Use of Action class  
       Actions builder = new Actions(driver);
       builder.moveToElement(Menu).build().perform();
//Move your mouse on Testing Services 
       driver.findElement(By.xpath("//*[@id='ctl00_Header1_HorizontalNavigation1_Menu_m0_m2']/span")).click();
       Submenu.click();
//Click on Testspotlight 
       }    
       }

}

Friday, 19 December 2014

[SeleniumWebDriver] No Such Element element Exception

Many of the Time Selenium users get this Problem

org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with

At that time first you need to Check if that elements is Present or Not on which you want to click or Perform any action

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestingSubmenu {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.neogenomics.com/solutions-overview.htm");
//Go to that website
        driver.findElement(By.xpath("//*[@id='ctl00_Header1_HorizontalNavigation1_Menu_m0_m2']/span")).click();
//Find xpath and click
After running this code you will get this Exception Element not visible.
Solution for this 
First You need to check whether that element is Present or Not
By using this is Displayed function in Selenium WebDriver You can find element is Present or not
If that element returns true then you can perform action on it.If it returns false then it means it is a hidden element.So you need to use Mouse Hover on that element.

//Here is the code
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestingSubmenu {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.neogenomics.com/solutions-overview.htm");
    Boolean submenu =     driver.findElement(By.xpath("//*[@id='ctl00_Header1_HorizontalNavigation1_Menu_m0_m2']/span")).isDisplayed();
       System.out.println(submenu);
       }
}

Tuesday, 16 December 2014

How to Download file in Selenium webdriver

How to download file in Selenium 

Many times you need to download a file like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text file, etc.So we need to follow some steps. Manually when we click on link to download file, It will show us dialogue to save file.
Generally this dialog box is in Firefox Browser.Manually just we have to click on save file and then file will be download on particular location.
But How Selenium Webdriver works
Selenium Webdriver do not have any feature to handle this save file dialogue.But Selenium can handle this dialog box and we can download  any file Webdriver's has Inbuilt class FirefoxProfile and some methods.By using some methods of FirefoxProfile we can download file.
Firefox profile methods


Before downloading a file in Firefox browser we should know MIME type of that file.Generally we use Mime type here 
//profile.setPreference("browser.helperApps.neverAsk.saveToDisk","SpecifyMIME TYPE HERE");
If file is of pdf file then write MIME Type is application/pdf
If you have any file first find out MIME type of your file from here.Even you can google for your MIME TYPE if you don't find here.
"text/plain;" //MIME types Of text File.

    "text/csv"); //MIME types Of CSV File.
Here is the code for Download File 
package demodownloadfile;
import java.io.File;

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.firefox.FirefoxProfile;

public class Downloading_File {
public static void main(String[] args) {
       //Create firefox profile
   FirefoxProfile profile = new FirefoxProfile(); 
   profile.setPreference("browser.download.folderList", 2);    
 //profile.setPreference("browser.download.dir","Specify your directory path here"); 
   profile.setPreference("browser.download.dir","E:\\downloadfile");    
     //Set path where you want to download file 
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/x-rar-compressed,application/octet-stream,application/csv,text/csv");
//Here i have explained some MIME type 
   WebDriver driver = new FirefoxDriver(profile);
   driver.get("http://www.winzip.com/landing/open-rar-file.html");
 //Go to url
   driver.findElement(By.xpath("//*[@id='downloadlink']/img")).click(); 
  //click on file link and download file  

}}
//Now your File has been Downloaded

Thursday, 11 December 2014

Page Factory(Pom)

Page Factory in Selenium 

In order to provide additional support for the Page Object pattern, the package org.openqa.selenium’ has a PageFactory Class. One can import the PageFactory class in Java using the following statement
import org.openqa.selenium.support.PageFactory;
By importing this package we can use multiple pages just we have to make an object of that class.
Let me take an example
Here If my page name is Login then i will call as 
Login l = PageFactory.initElements(driver, Login.class);
Generally we make the object of that class and use but in page factory we use init method.
You can also  this Page Factory as Reference.
In page factory we define Webelements like this.
Annotations in PageFactory are like this:



We use annotation@FindBy 
If we use locator as xpath then we will write 
@FindBy(how = How.XPATH, using = "//*[@value='First name']")
WebElement firstname;
how = How.XPATH, [We can define locators  as How.ID,How.name,How.css etc]
In using we have to define which locator we are using id,xpath name,css etc.
using = //*[@value='First name']
If we use locator By name Then we will write 
@FindBy(how = How.NAME, using = "firstname")
WebElement firstname;

We don't used driver.findelements();

We simply call these as:
 firstname.sendKeys("Ritika");

How to implement Page factory
  •  Create a ‘New Package file and name it as ‘pageobject’ by right click on the Project and select New > Package.


  •  Create a ‘New Class’ file and refer the name to the actual page from the test object, by right click on the above created Package and select New > Class. In our case it as FacebookRegistration
//Here is code of page factory 
package pageobject;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.Select;

public class FacebookRegistration {
WebDriver driver;
public FacebookRegistration(WebDriver ldriver){
this.driver= ldriver;
}
 
@FindBy(how = How.XPATH, using = "//*[@value='First name']")
WebElement firstname;
@FindBy(how = How.XPATH, using = "//*[@value='Last name']")
WebElement lastname;
@FindBy(how = How.XPATH, using = "//*[@value='Email or mobile number']")
WebElement email;
@FindBy(how = How.XPATH, using = "//*[@value='Re-enter email or mobile number']")
WebElement reemail;
@FindBy(how = How.XPATH, using = "//*[@value='New password']")
WebElement NewPassword;
@FindBy(how = How.XPATH, using = "//*[@id='month']")
WebElement month;
@FindBy(how = How.XPATH, using = "//*[@id='day']")
WebElement day;
@FindBy(how = How.XPATH, using = "//*[@id='year']")
WebElement year;
@FindBy(how = How.XPATH, using = "//*[@id='u_0_d']")
WebElement female;
@FindBy(how = How.XPATH, using = "//button[@name='websubmit']")
WebElement signup;
 
// Type firstname
public void typefirstname(String fname) {
firstname.sendKeys(fname);
}
// Type lastname
public void typelastname(String lstname) {
lastname.sendKeys(lstname);
}
// Type email
public void typeemail(String emailid) {
email.sendKeys(emailid);
}//Typereemail
public void typeremail(String remailid) {
reemail.sendKeys(remailid);
}
//typenewpassword
public void typenewPassword(String newpassrd) {
NewPassword.sendKeys(newpassrd);
}
//selectmonth
public void selectmonth(String mont){
month.sendKeys(mont);
}
//Select date 
public void selectdate(String date){
day.sendKeys(date);
}
//selecting year
public void selectyear(String yea){
year.sendKeys(yea);
}
//clicking on femaleradiobutton  
public void ClickingGender(){
female.click();
}
//clicking sign up button  
public void clicksignup(){
signup.click();
}
 
}
/In this We have created a Registration page of Facebook Now we need to call this page in our Testcase.Generally we create pages in page object factory and after that we call that pages in Testcase.
  •  Create a ‘New Package file and name it as ‘pageobjectframework’ by right click on the Project and select New > Package.
  •  Create a ‘New Class‘ and name it as TestCase by right click on the ‘pageobjectFramework Package and select New > Class.
package pageobjectframework;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pageobject.FacebookRegistration;


public class TestCase {
WebDriver driver;
@BeforeTest 
    public void openBrowser(){
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://www.facebook.com");
    }
//This test will fill the sign up page of facebook login
@Test
public void registerDetails(){
//By this init method we can call our pages in Page factory.
FacebookRegistration fo = PageFactory.initElements(driver, FacebookRegistration.class);
fo.typefirstname("Ritika");
fo.typelastname("Gulati");
fo.typenewPassword("seleniumgyan");
fo.typeemail("submityouremailid@gmail.com");
fo.typeremail("submityouremailid@gmail.com");
fo.selectmonth("Jul");
fo.selectdate("22");
fo.selectyear("1991");
fo.ClickingGender();
fo.clicksignup();
}}

Popular Posts

 
subscribe
Subscribe Us
emailSubscribe to our mailing list to get the updates to your email inbox... We can't wait more to have your email in our subscribers email list. Just put your nice email in below box: