Automation Using Selenium Webdriver

Wednesday, 12 October 2016

Download And Save Image Using Selenium WebDriver + Actions + Robot

Interaction API tutorial section. For downloading Image, We will use same WebDriver Actions class with java robot class.
For saving Image from web page In selenium webdriver, We have to perform bellow given actions.

    Right click on Image
    Select "Save Image As" option from mouse right click context menu.
    Enter file name In save Image dialog
    Press Save button.

Right click on Image using contextClick() method of Actions class
As you know, "Save Image As" option will display when you right click on any Image. We will use contextClick() method of WebDriver Actions class to right click on Image as shown In bellow Image.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Actions_Test {

 WebDriver driver;
 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();    
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get("http://any website");
 }

 @Test
 public void Save_Image() throws IOException, InterruptedException, AWTException {
  //Locate Image
  WebElement Image =driver.findElement(By.xpath("//img[@border='0']"));
  //Rihgt click on Image using contextClick() method.
  Actions action= new Actions(driver);
  action.contextClick(Image).build().perform();
 
  //To perform press Ctrl + v keyboard button action.
  action.sendKeys(Keys.CONTROL, "v").build().perform();

  Thread.sleep(3000);
  Robot robot = new Robot();
  // To press D key.
  robot.keyPress(KeyEvent.VK_D);
  // To press : key.
  robot.keyPress(KeyEvent.VK_SHIFT);
  robot.keyPress(KeyEvent.VK_SEMICOLON);
  robot.keyRelease(KeyEvent.VK_SHIFT);
  // To press \ key.
  robot.keyPress(KeyEvent.VK_BACK_SLASH);
  // To press "test" key one by one.
  robot.keyPress(KeyEvent.VK_T);
  robot.keyPress(KeyEvent.VK_E);
  robot.keyPress(KeyEvent.VK_S);
  robot.keyPress(KeyEvent.VK_T);
  // To press Save button.
  robot.keyPress(KeyEvent.VK_ENTER); 
 }
}
}

How to verify a Text present in the loaded page through Web Driver

       How to verify a Text present in the loaded page through Web Driver
   
Verify  "Flights"  a text present in a goibibo.com

package exmp;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class VerifyTextWebpage {

public static void main(String[] args) {
// TODO Auto-generated method s
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.goibibo.com/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();

String expText="Flights";
//verify flights text Available are not
String actText=driver.findElement(By.xpath("html/body/div[1]/div[1]/ul/li[1]/a/span")).getText();
if(actText.contains(expText)){
System.out.println("1)Expected Text"+expText+"Preent in the page");
}else{
System.out.println("1)Expected Text"+expText+" not Preent in the page");
}

}

}

//OutPut:1)Expected TextFlightsPreent in the page





Tuesday, 11 October 2016

How To Zoom In And Zoom Out Page In Selenium Test

 How To Zoom In And Zoom Out Page In Selenium Test

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ZoomBrowser {
 WebDriver driver;

 @BeforeTest
 public void setup() throws Exception {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get("http://google.com/");
 }

 @Test
 public void getScrollStatus(){
  //Call zooming functions to zoom in and out page.
  zoomIn(); 
  zoomOut();
  zoomOut();
  set100();
 }

 public void zoomIn(){
  //To zoom In page 4 time using CTRL and + keys.
  for(int i=0; i<4; i++){  
  driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
  }
 }

 public void zoomOut(){
  //To zoom out page 4 time using CTRL and - keys.
  for(int i=0; i<4; i++){
   driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
  }
 }

 public void set100(){
  //To set browser to default zoom level 100%
  driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0"));
 }
}

How to explain the Data driven framework to the interviewer

In my project We are  Using  Data Driven Framework Say like ::
Basically  I involved 3 stages- 
 1.Design the framework::
( eclipse create a java project by name abc,under project create like 
      project name---->package name---->class name--->,)
add all external jar file selenium,Apache POI jars,and TestNG Framework add all jars
To perform the validation, we create one more class Assertion. Whenever we need to perform validation we need to call assertText() or assertTitle() present under the Assertion class. (Assert.assertEquals())
 2.implementing the framework ::

This is where actual implementation of the framework start. While going thru the manual testcases we note down the common repeated steps and make those steps as a project specific methods. Even if one step is repeating , may be in same testcase or other testcase make it as a method. Then write the test script for all the manual test cases.

 

3.execution process ::
Right click on the project, navigate to TestNG → convert to TestNG → give the proper suite name and test name and click on finish. Then execute this xml file (ctrl+f11) or right click and run as TestNG Suite. Or to run thru cmd → navigate till project then give this commnd-

4.check failed testcase and execute agian


what is uses data driven in your project

Well defined architectural design
Less time to test large data
Script execution in multiple environments
Easier, faster, and efficient analysis of result logs
Communication of results

Easy debugging and script maintenance

Data Driven framework-------->

In my Project  is  too deep with pages , however each page can have scenarios that need to be tested with large test data sets, we would want to write automation scripts with a focus on test data aka. data-driven. Tools like Selenium already have excel sheet parsing etc that loops through rows and the same test case is executed for each data-set. It helps me to  excel is the most optimum way to handle test data.


Monday, 10 October 2016

CTS Last Week Asked 2 Years Selenium Testing Position


  CTS Last Week Asked 2 Years Selenium Testing Position 

1. Can you write a dynamic xpath
2. What frame work is used in your project
3. Can you write a build.Xml
4. Write a query for self join
5. A flex board is produced from factory how do you test that
6. Write a code where there are 2 set's of key value pair, print the value only if keys and values are same
7. Have you worked on Unix
8. What are the advantages of pom frame work in selenium
9. As a qa engineer do you think known the backend process is important
10. What is non functional testing
11.Using which keyword we acquire the behavior of one class to another class

Execute Failed test cases using selenium Real-time Example

Most of the time we have faced this question in interviews that Can we execute only failed test cases in Selenium or can we identify only failed test cases in Selenium and re-run them.



I really love this feature of TestNG that you can run only failed test cases explicitly without any code. This can be easily done by running one simple testng-failed.xml.


                                    Execute Failed test cases using Selenium
                                           Real-time Example


Take an example that you have one test suite of 100 test cases and once you start execution of test suite there  are a number of chances that some test cases will fail.Consider 15 test cases are failing out of 100 now you need to check why these test cases are failing so that you can analyze and find out the reason why they have failed.

Note- Your script can fail due to so many reasons some of them are

1- Some locator has been changed in application because the application is getting new feature- so in this case you need to modify your script in other words you have to refine your script.

You can not avoid maintenance of test script you always have to maintain your scripts
2- Either functionality has been broken- in this case, you have to raise a defect and assign to the respective person.

Execute Failed test cases using Selenium
Steps

1-If your test cases are failing then once all test suite completed then you have to refresh your project . Right click on project > Click on refresh or Select project and press f5.

2-Check test-output folder, at last, you will get testng-failed.xml

3- Now simply run testng-failed.xml.


           

How to run testng-failed.xml
We don’t have to perform any other activity once you will  get testng-failed.xml double click on this and analyze which test case are failing and why . Then modify your script and run it.

To run above xml simple right click on xml then Select run as then TestNG Suite.


or more info visit TestNG official website
Thanks for visiting my blog. Keep visiting.
Please comment below if you finding any issue. Have a nice day ðŸ™‚

How to create dependency between testcases in Selenium




I am sure you must be confused with Title like How to create a dependency between test cases in Selenium but in this post we will see this through example.

In real time, you will come across many situation where you have to create test cases which are dependent on the previous test case.

Take an example I have 3 test case.

First one which verify login credential and start application
Second test case check some validation  or do some activity
Third test case simply just for log-out activity.

If my first test case does not work (failed) that it does not make any sense to run second and third test case so in these type of scenarios you can use dependency between test case.

How can I do this?

TestNG already comes with this features so you can use the same with @Test annotations


Syntax- @Test(dependsOnMethods={"loginTestCase"})

public void testAccount()
{

// sample code

}
Syntax- @Test(dependsOnMethods={"loginTestCase"})

public void testAccount()
{

// sample code

}
How to create dependency between test cases in Selenium



It means this test case name testAccount depends on test case whose name is loginTestCase so until loginTestCase will not execute successfully this test case won’t execute so if loginTestCase will pass this test case will execute and if loginTestCase will fail then this test case won’t execute and runner will skip this test cases and this test case will come under skip test cases.

Let’s implement the same


package Demo;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMultiple {

@Test
public void testLogin()
{

System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()
{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})
public void testLogout()
{
System.out.println("logout");

}

}


package Demo;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMultiple {

@Test
public void testLogin()
{

System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()
{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})
public void testLogout()
{
System.out.println("logout");

}

}


In the above scenario if testLogin will pass then only testAccount will execute and testLogout will only execute of testLogin and testAccount will  be executed

but if testLogin will fail due to some error or exception the testAccount will not be executed and this test case will skip and testLogout is dependent on testLogin and testAccount so now this will also come into skipped category

Let’s implement again


import org.testng.Assert;
import org.testng.annotations.Test;

public class TestApplication {

@Test
public void testLogin()

{
Assert.assertEquals("Selenium", "Selnium");
System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()

{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})

public void testLogout()

{
System.out.println("logout");
}
}

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestApplication {

@Test
public void testLogin()

{
Assert.assertEquals("Selenium", "Selnium");
System.out.println("login done");

}

@Test(dependsOnMethods={"testLogin"})
public void testAccount()

{
System.out.println("Account has been created");

}

@Test(dependsOnMethods={"testLogin","testAccount"})

public void testLogout()

{
System.out.println("logout");

}
}


Output

FAILED: testLogin
java.lang.AssertionError: expected [Selnium] but found [Selenium]
at org.testng.Assert.fail(Assert.java:94)
SKIPPED: testAccount
SKIPPED: testLogout

===============================================
Default test
Tests run: 3, Failures: 1, Skips: 2
===============================================

===============================================
Default suite
Total tests run: 3, Failures: 1, Skips: 2
===============================================

OUTPUT in HTML