Selenium Webdriver Commands


This is the key of Selenium Webdriver Commands. These are the most commands which will help you in writing your scripts. 


Selenium WebDriver Commands
Selenium Webdriver Commands

What is HTMLUnitDriver?

HTMLUnitDriver is fastest (50% faster than Firefox), lightweight, platform independent. However, we don't use it. We always prefer to use Firefox, Chrome, IE but not HTMLUnitDriver


Do you know why?? 

Here is the answer:


HTML Unit Browser is a head less browser (you can say browser without User Interface) i.e it doesn't open any window, as it runs on the background and interacts with HTML. So, you have to see results in console. Moreover, you won't be able to take screenshots.

Even you couldn't ask others to search entire console box to find out errors.

How to Login and Logout in Gmail

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Openbrowser
{
public static void main(String args[]) throws InterruptedException
{
WebDriver driver=new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);


driver.get("http://gmail.com/");

driver.findElement(By.id("Email")).sendKeys("");

driver.findElement(By.id("Passwd")).sendKeys("");

driver.findElement(By.id("signIn")).click();

Thread.sleep(4000);

driver.findElement(By.xpath("//*@id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a/span")).click();

driver.findElement(By.id("gb_71")).click();

}
}

How to setup Classpath for Java in Windows 7?

We all know the importance of CLASSPATH for Java. Setting PATH/CLASSPATH is very easy if we have the correct steps. I've listed down the steps which will help you to set CLASSPATH/PATH for Java:

 
Step 1: Download Java or JDK from the following URL according to your computer configuration:
Step 2: Install it by click on setup.exe and following the steps.
Step 3: By default JDK installs at "C:\Program Files\Java\jdkxxx.xx" location only. Unless we change the location at the time of installation.
Step 4Go to JDK installed location, open bin folder available at the location. Now, copy the path.
Step 5: Right-click on My Computer icon available at your desktop and select Properties.
Step 6: Now, click on Advanced System Settings and click on Advanced tab from the dialog box opened
Step 7: Click on Environment Variables and then System Variables.

Step 8: Edit path and add the copied bin (which we did in Step 4) in that. Below are some images to help you:



Step 9: Click on OK of Environment Variables window and System Properties window.
Step 10: To verify whether Classpath or path of java is set up correctly or not.

Open Command Prompt and enter java -version. You'll find a statement like mentioned below:

java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)

Basic Selenium Commands

Below are some basic commands of selenium which you can try and use while writing your script for automation of any website. If you face any problem, you can raise your query by completing the form available :

  1. driver.get("http://www.google.com"); To open an application
  2. driver.findElement(By.id("passwd-id")); Finding Element using Id
  3. driver.findElement(By.name("passwd")); Finding Element using Name
  4. driver.findElement(By.xpath("//input[@id=’passwd-id’]")); Finding Element using Xpath
  5. element.sendKeys("some text"); To type some data
  6. element.clear(); clear thecontents of a text field or textarea
  7. driver.findElement(By.xpath("//select")); Selecting the value
  8. select.findElements(By.tagName("option")); Selecting the value
  9. select.deselectAll(); This will deselect all OPTIONs from the first SELECT on the page
  10. select.selectByVisibleText("Edam"); select the OPTION withthe displayed text of “Edam”
  11. findElement(By.id("submit")).click(); To click on Any button/Link
  12. driver.switchTo().window("windowName"); Moving from one window to another window
  13. driver.switchTo().frame("frameName"); swing from frame to frame (or into iframes)
  14. driver.switchTo().frame("frameName.0.child"); to access subframes by separating the path with a dot, and you can specify the frame by itsindex too.
  15. driver.switchTo().alert(); Handling Alerts
  16. driver.navigate().to("http://www.example.com"); To Navigate Paeticular URL
  17. driver.navigate().forward(); To Navigate Forward
  18. driver.navigate().back(); To Navigate Backword
  19. driver.close(); Closes the current window
  20. driver.quit(); Quits the driver and closes every associated window.
  21. driver.switch_to_alert(); Switches focus to an alert on the page.
  22. driver.refresh(); Refreshes the current page.
  23. webdriver.manage().window().setPosition(new Point(-2000, 0); to minimize browser window

Access Modifiers in Java

We always use Public, Private, Protected in our Selenium scripts. Before using these, we should know how and where to use these access modifiers. Here is the table showing where we can call these modifiers:


Access Modifier
within class
within package
outside package by 
subclass only
outside 
package
Private
Y
N
N
N
Default
Y
Y
N
N
Protected
Y
Y
Y
N
Public
Y
Y
Y
Y

Interview Questions and Answers on Automation Testing

Click on the questions below to get the answers


1) What is Automation ?

Answer: In general, it is the process of implementing particular work automatically by using a machine, to reduce the need of human work in the production of goods and services.
2) What is meant by Automation in software testing ?
Answer: It is a process of testing an application(executing the tests, comparing expected and actual results under some controlled conditions and generating the reports) automatically by using a 'Tool' to reduce the need of human effort. This tool may be Selenium / QTP / RFT / SilkTest etc.
3) Why do we need automation in software testing ?
Answer: Humans can do mistakes. If a work is repetitive then we may skip some work intentionally or unintentionally due to time pressure, boring task, etc. In order to overcome these problems 'automation testing' has been introduced to reduce manual task, to save cost and time, to improve accuracy, to perform repetitive execution of tests, to customize defect reporting etc. and hence automation is needed, as it replaces human with great features.
4) Which type of testing can be Automated ?
Answer: We can automate Regression testing, Functional testing, Stress testing, Performance testing, Load testing, Smoke testing, Compatibility testing, Data-Driven testing etc.
5) When to do automation testing ?
Answer: It is not always advantageous to automate test cases. We can do automation:
- When the application is stable.
- For long term projects.
- When you have lot of regression work.
- When the scenario is easily debuggable.
6) What are the advantages and disadvantages of Automation Testing ?
Answer:

Advantages :
- Reduces human resources.
- Using an automation tool, test scripts can be executed faster when compared to manual execution and hence saves time.
- Repeatable execution of tests may lead to make mistakes when it is done manually but when we automate the same task, accuracy will be improved.
- Test cases can be reused in various versions of software which saves time and cost.

Disadvantages:
- Unemployment rate increases as machine replaces human.
- It is not so easy to write automation test scripts, it requires skilled and experienced resources.
- We cannot automate everything as it is advantageous only for repeatable and reusable test cases.
- Initial cost for automation is very high unless it is open source.
- Debugging skills should be high otherwise its effect will be dangerous (mainly it kills time, so, we cannot reach dead-line).

7) Name some test automation tools? 

Answer:

- Selenium (Open Source)
- HP QuickTest Professional (Commercial)
- IBM Rational Functional Tester (Commercial)
- HP WinRunner (Commercial)
- SilkTest (Commercial)
- HTTP Test Tool (Open Source)
- WATIR (Open Source)
- Maveryx (Open Source)
- eggPlant (Commercial)

8) What kind of tests should NOT be automated? 

Answer:

- Automating tests that only need to be executed once doesn't make sense.
- Tests without predictable results – test automation should give us confidence in the results of the tests. If there are intermittent failures then the tests cannot be reliable.
- Tests that need to be verified visually
- Tests that need to be executed quickly. At first, writing an automated test takes longer. If we want a quick check, we should test it manually however, if that test is a good one which should be run regularly, then it should be automated in time
- Usability Testing – at times it becomes impossible to perform testing by automation as the computer cannot efficiently judge if the system is of any use to its users.

Generate Random Data

In your scripts, you always want to generate random data to automate SignUp forms, below is code to generate random password. If you need script to generate data to complete forms like available here, do write an email to me:

--------------

public static void main(String[] args) {

//can put any array below depending on requirement
String array = "abcde1234567890~!@#$%^&*()_+";

//calculates its length
int i = array.length();

 //password with length 10
for (int j =0; j<=10; j++)

//randomly picking up 10 characters
{
 int k = (int)(Math.random()*i);
char pass = array.charAt(k);
 System.out.print(pass);
 }
 }

How to Set up a Project in Eclipse?

¨> Open eclipse (To download eclipse 64 bit or 32 bit, click here)

¨> Right click on Package Explorer > New > Java Project
¨> Give a Project name and click Next
¨> Go to Selenium downloads page and download Java Language bindings (Or Click Here to download Selenium latest jars)
¨> Extract it in your local drive
¨> Right Click in your project > Properties
¨> Java Build Path > Libraries
¨> Click “Add Library..” button and add JAR files (include files in “libs” folder)
¨> After import JAR files, you can see “Referenced Libraries” folder

How to get data from an Excel sheet?

If you're looking how to pick username and passwords or any data from an excel sheet then below steps will help you out:


1) Download J-Excel jar (What is J-Excel), you can get the path to download J-Excel jar by clicking here
2) Now, add this jar to your build path. You can look for the steps.
3) Create a new class and add below code:
public class Excel {
static Sheet s ;
 public static void main(String[] args) throws BiffException, IOException {

FileInputStream fis = new FileInputStream("C:\\Users\\DELL\\Desktop\\r.xls");
Workbook w = Workbook.getWorkbook(fis);
s = w.getSheet(0);


for (int i=0; i<=s.getRows(); i++)
{
 String username = s.getCell(0, i).getContents();
 System.out.println(username);
 String username1 = s.getCell(1, i).getContents();
 System.out.println(username1);

}
}

Difference between Jexcel and Apache POI


JExcel

Apache POI

  • It doesn’t support Excel 2007 and Xlsx format. It supports only Excel 2003 and .Xls format

  • It supports both

  • JXL doesn’t support Conditional formatting

  • It supports

  • JXL API was last updated in 2009

  • Apache POI is actively maintained

  • It doesn't support rich text formatting

  • Apache POI supports it

  • It has very less documents and examples as compare to Apache POI

  • It has extensive set of documents and examples

You can download Apache POI jar by clicking here
You can download JExcel jars by clicking here

Example of JExcel Click Here







How to Zoom In and Zoom Out in Website

In case, you want to zoom in and out in any website using Selenium. You can follow below commands:


To Zoom In:

WebElement Sel= driver.findElement(By.tagName("html"));
sel.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));

To Zoom Out to normal page, use below command:

html.sel(Keys.chord(Keys.CONTROL, "0"));

This can be useful when you need to pin point something while showing your automation framework to any user. 

TestNG Error Codes

We write automation framework using TestNG and when we run it we get errorssometimes. So, it becomes important for us to know about error messages. 


I have put some of the error messages that we get when we go wrong and execute TestNG XML file:

1.If two tests are having the same name then we see below error

at org.testng.TestNG.checkTestNames(TestNG.java:981)
at org.testng.TestNG.sanityCheck(TestNG.java:970)
at org.testng.TestNG.run(TestNG.java:1002)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:109)

2.If the testname doesnot enclosed in double quotes("") then we get below error


The value of attribute "name" associated with an element type "null" must not contain the '<' character.
 at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
 at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: The value of attribute "name" associated with an element type "null" must not contain the '<' character.
atcom.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)

3.If the class name doesnt end with "/" character then we will see below error

org.testng.TestNGException: org.xml.sax.SAXParseException: The end-tag for element type "class" must end with a '>' delimiter.
 at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
 at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: The end-tag for element type "class" must end with a '>' delimiter.

4. If there is no space between parameter name and value  fields then we will see below error 

Ex   :  
org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "parameter" must be followed by either attribute specifications, ">" or "/>".
 at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
 at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "parameter" must be followed by either attribute specifications, ">" or "/>".

5.If the parameter attribute doesnt end with "/" character then we will see below error

org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".
 at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
 at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".

6. If the two parameters have the same name and value attributes then we will see below error

org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".
 at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
 at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".

7.Make sure there are no spaces between "/" and  ">".If there are any spaces then we will see below error.

org.testng.TestNGException: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".
 at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:335)
 at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
Caused by: org.xml.sax.SAXParseException: Element type "class" must be followed by either attribute specifications, ">" or "/>".

What is the difference between Xpath and DOM (Document Object Model)?

This is the question asked in most of the interviews of Selenium:

DOM: 

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Objects in the DOM tree may be addressed and manipulated by using methods on the objects.

Ex: var element=document.getElementById("intro");

XPATH: 

XPath, the XML Path Language, is a query language for selecting nodes from an XML document. In addition, XPath may be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document.

How to register in Facebook?

Below is the code to make an account on Facebook using Selenium Wedriver:


public class FacebookRegistration {

public static void main(String[]args)
{
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[@value='First Name']")).sendKeys("raj");
driver.findElement(By.xpath("//*[@value='Last Name']")).sendKeys("raja");
driver.findElement(By.xpath("//*[@value='Your email address']")).sendKeys("raja@mail.com");
driver.findElement(By.xpath("//*[@value='Re-enter email address']")).sendKeys("raja@mail.com");
driver.findElement(By.xpath("//*[@value='New Password']")).sendKeys("A123a!");
new Select(driver.findElement(By.xpath("//*[@name='birthday_day']"))).selectByValue("1");
new Select(driver.findElement(By.xpath("//*[@id='month']"))).selectByValue("2");
new Select(driver.findElement(By.xpath("//*[@id='year']"))).selectByValue("1987");
driver.findElement(By.xpath("//*[@id='u_0_g']/span[1]/label")).click();
driver.findElement(By.xpath("//*[@id='u_0_i']")).click();
}
}

How to handle Select in Selenium

Example of using Select in Selenium 

public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.mobikwik.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[@id='mobile_number']")).sendKeys("9910979218");
driver.findElement(By.xpath("//*[@id='mobile_amount']")).sendKeys("10");
WebElement operator = driver.findElement(By.xpath("//*[@id='mobile_operator']"));
Select option = new Select(operator);
option.selectByVisibleText("Idea");
Thread.sleep(5000);
driver.close();
}

How to handle multiple windows in Selenium?

Example of handling Multiple Windows in Selenium:

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("https://www.abc.com/");
driver.manage().window().maximize();
String Window1 = driver.getWindowHandle();
driver.findElement(By.linkText("Contact us Now")).click();
for (String Window2 : driver.getWindowHandles())
{
driver.switchTo().window(Window2);
}
driver.findElement(By.xpath("//*[@id='bigin']")).sendKeys("abcde");
Thread.sleep(5000);
driver.close();
driver.switchTo().window(Window1);
driver.getTitle();
Thread.sleep(3000);
driver.close();
}

How to handle iFrames in Selenium?

A basic example of handling frames at www.espncricinfo.com


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

public class Abc
{
public static void main(String args[])
{
WebDriver driver=new FirefoxDriver();
driver.get("http://www.cricinfo.com/");
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);
driver.findElement(By.linkText("Countries")).click();
driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='ciHomeContentrhs']/iframe")));
driver.findElement(By.linkText("Cricinfo")).click();
}
}

Mouse Hover in selenium

public static void main(String[] args) throws InterruptedException {


WebDriver driver = new FirefoxDriver();
driver.get("http://www.timeanddate.com/");
driver.manage().window().maximize();
WebElement menu = driver.findElement(By.xpath("//*[@id='nav']/ul/li[3]/a"));
Actions action = new Actions(driver);
action.moveToElement(menu).perform();
WebElement submenu = driver.findElement(By.xpath("//*[@id='nav']/ul/li[3]/ul/li[4]/a"));
action.moveToElement(submenu).click().perform();

Thread.sleep(5000);
driver.close();
}

Get all links of a Webpage using Selenium

How to test links of any website?

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
List links = driver.findElements(By.tagName("a"));
System.out.println(links.size());    // to check the number of links present at webpage
for (int i = 1; i {
System.out.println(links.get(i).getText());
}
}

How to Clear Browser Cookies with Selenium Web Driver

This code below applies to Selenium .Net.
Clearing browser cookies before starting your test is important to test the application in real life scenarios. If you are using Selenium Web Driver for your web test automation, you can use this method below to clear all cookies.
Let's assume that your Selenium Web Driver name is _webDriver; You can create a void method below and then call the method before you navigate to the application URL.
  1. public void ClearBrowserCache()
  2. { _webDriver.Manage().Cookies.DeleteAllCookies(); //delete all cookies
  3. Thread.Sleep(5000); //wait 5 seconds to clear cookies. }

How to handle Cookies using Selenium Webdriver?

  • Sometimes, we face issues because of cookies session created by Selenium scripts and we have to delete them using Selenium Webdriver. So, here is the code:

public class Cookies
{
    public static void main(String[] args) 
    {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://in.quikr.com/");
        
        Set cookies=driver.manage().getCookies();
        
        //To fetch out the number of cookies used by this site
        System.out.println("Number of cookies in this site "+cookies.size());
        
     //Using advanced For Loop
        for(Cookie cookie:cookies)
        {
            System.out.println(cookie.getName()+" "+cookie.getValue());
            
            //This will delete cookie By Name
            driver.manage().deleteCookieNamed(cookie.getName());
            
             }
         //This will delete all cookies.
        driver.manage().deleteAllCookies();
           } }

SVN(Sub Version) -Test Script repository

SVN is a repository (Test Script repository). Usually SVN server is installed in lab server and to this server, Access will be given to Automation Test Engineer.

Steps to download SVN server-

Step1- open this link - http://www.visualsvn.com/server/download/
Step2- click on download now.



Step3- click on save.



Step4- Now click on the downloaded file and follow the install instruction (just click on next next).



Step5- After installation, SVN server will launch by default if not then launch it. Then right click on Repositories and click on Create New Repository.











Step6- Give the Repository name. (for ex- give Repository name as SpiceJet.) then click on next.





Step7- Select Single-project repository and then click on next.




Step8- Then click on Create




Step9- Click on finish.



Step10- Go to user --> Right click --> create user --> give username and password then click on OK.






Note- Now Go to eclipse. In order to integrate eclipse with SVN server. It is required to download another plugin called as Subclipse in eclipse.

Steps to download Subclipse

Step1- Open Eclipse -> go to Help -> click on Eclipse Marketplace 



Step2- in Find textbox type Subclipse and click on Go.



Step3-  Under Subclipse click on install.




Step4- Just click on next next and restart the eclipse after installation.
Step5- Now go to Window in eclipse -> show view -> click on Other



Step6- Expand SVN -> select SVN Repositories -> click on OK.



Step7- Under SVN Repositories in menu bar, click on Add SVN Repositoy.





Give the Url.

Note- To get the Url, goto SVN Server, select the created workspace -> right click -> Copy URL to Clipboard -> this will copy the Url -> now paste this Url to the above Url text box.




Step8- After pasting the Url , click on Finish.


Step9- That's all. You are done with the setup.
Step10- Create a project in eclipse. In order to upload all the files to SVN server, select the project -> right click -> go to Team -> click on Share Project




Step11- Select SVN and click on Next.




Step12- select 'Use existing repository locations' and select the repository to which you want to add your project and click on next.




Step13- Click on finish.




Step14- After wait for a while, it has added your project to SVN server. Go back to SVN server and refresh it, you will find your project name there.

Step15- Now just right click on any file/package of the Project -> go to Team -> click on Commit. -> Click on OK.

For ex- Here Owler is the Project and library is the file which has been added to SVN.





Step16- Finally added the project to SVN server. The item which has been added to SVN server, it will look like below.