Saturday, 30 August 2014

Swapping of Two Numbers without Using Temp Variable

package Logs;

public class Swapping {

    public static void main(String a[]){
        int x = 10;
        int y = 20;
        System.out.println("Before swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
        x = x+y;
        y=x-y;
        x=x-y;
        System.out.println("After swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
    }
}

OutPut:

Before swap:
x value: 10
y value: 20
After swap:
x value: 20

y value: 10

Palindrome Example in java


package Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Palindrome  {
 public static void main(String [] args){
 try{
 BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
 System.out.println("Enter number");
 int num= Integer.parseInt(object.readLine());
 int n = num;
 int rev=0;
 System.out.println("Number: ");
 System.out.println(" "+ num);
 for (int i=0; i<=num; i++){
 int r=num%10;
 num=num/10;
 rev=rev*10+r;
 i=0;
 }
 System.out.println("After reversing the number: "+ " ");
 System.out.println(" "+ rev);
 if(n == rev){
 System.out.print("Number is palindrome!");
 }
 else{
 System.out.println("Number is not palindrome!");
 }
 }
 catch(Exception e){
 System.out.println("Out of range!");
 }
 }
}

Output:
1.
Number: 
 231
After reversing the number:  
 132
Number is not palindrome!


2.Enter number
252
Number: 
 252
After reversing the number:  
 252
Number is palindrome!

To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Windows Handler


                        In a page we will be handling the windows to achieve this the small piece of code is required.


package TestNG;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Demo7 {

public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("http://www.naukri.com");

Iterator<String> Wh = driver.getWindowHandles().iterator();
String Parent = Wh.next();
String Child1 = Wh.next();
String Child2 = Wh.next();

driver.switchTo().window(Child2);
driver.get("www.google.com/");
driver.close();

driver.switchTo().window(Child1);
driver.get("https://www.facebook.com/");
driver.close();

driver.switchTo().window(Parent);
driver.get("https://demo.vtiger.com/index.php#");
driver.close();

}
}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Bread Crumbs


                       This is used to know the exact location of the product .
               

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

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

driver.get("https://zovi.com/");

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

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

driver.findElement(By.linkText("Casual Shirts")).click();

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

String bcName=driver.findElement(By.xpath("//div[@id='breadcrumbs']")).getText();

if(bcName.contains("Home/Men/Shirts/Casuals"))

{

System.out.println("Pass");
}

else

{

System.out.println("Fail");
}
driver.close();
}




To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Friday, 29 August 2014

FireBug

  • It integrates with firefox  to edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.
  • CSS and Xpath of an web element can be found using firebug.
  • Once firebug is installed, firebug can be opened using F12 after opening the browser.
  • Using inspect button,  the  CSS and Xpath can be found of any web element.






To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Installation of Selenium IDE


  •  Go to http://seleniumhq.org/download/.
  •  Click on the download link for Selenium IDE. You may get a message saying Firefox prevented this site (seleniumhq.org) from asking you to install software on your computer. If you do, click on the Allow button. 
  • When downloading from Firefox, you’ll be presented with the following window. Select Install Now.








The Firefox Add-ons window pops up, first showing a progress bar, and when the download is complete, displays the following. Restart Firefox.






After Firefox reboots you will find the Selenium-IDE listed under the Firefox Tools menu.







To run the Selenium-IDE, simply select it from the Firefox Tools menu. It opens as follows with an empty script-editing window and a menu for loading, or creating new test cases.
The three major components of Selenium IDE are  Command, Target and Value.




The toolbar contains buttons for controlling the execution of your test cases, including a step feature for debugging your test cases. The right-most button, the one with the red-dot, is the record button.






Base URL—This is the URL that the test will start. All open commands will be relative to the Base URL unless a full path is inserted in the open command. 

Speed Slider—This is the slider under the Fast Slow labels on the screen. 





- Run all the tests in the IDE.
-Run a single test in the IDE. 

 -Pause a test that is currently running. 

-Step through the test once it has paused.

-This is the record button. It will be engaged when the test is recording.

  • The Edit menu allows copy, paste, delete, undo, and select all operations for editing the commands in your test case. 
  • The Options menu allows the changing of settings. You can set the timeout value for certain commands, add user-defined user extensions to the base set of Selenium commands, and specify the format (language) used when saving your test cases. 
  • The Help menu is the standard Firefox Help menu; only one item on this menu–UI-Element Documentation–pertains to Selenium-IDE.
  • Test script is displayed in the test case pane.
  •  It has two tabs, one for displaying the command and their parameters in a readable “table” format.




  • The other tab - Source displays the test case in the native format in which the file will be stored. 
  • By default, this is HTML although it can be changed to a programming language such as Java or C#, or a scripting language like Python. 
  • The Source view also allows one to edit the test case in its raw form, including copy, cut and paste operations.
  • The bottom pane is used for four different functions–Log, Reference, UI-Element, and Rollup–depending on which tab is selected.
  • Log : When you run your test case, error messages and information messages showing the progress are displayed in this pane automatically.
  • Reference: The Reference tab is the default selection whenever you are entering or modifying Selenese commands and parameters in Table mode. In Table mode, the Reference pane will display documentation on the current command. 

To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Thursday, 28 August 2014

Invocation Count Example in SeleniumWeb driver

It tells that how many times that an test case can be executed.To determine that a small piece of code is given below.

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


    public class test{
       private WebDriver driver;
       @Test(invocationCount=4)
public void logo() throws Exception {
             driver = new FirefoxDriver();

driver.get("http://www.hdfcbank.com/");

driver.findElement(By.className(("logo"))).click();

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


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

How to handle dropdown text into notepad in SeleniumWebDriver

 In an Web application we are trying to contents present in dropdown to notepad.
The piece of code is required is given below.

package TestNG;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

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 Dropdowntonotepad {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.etouch.net/home/index.html");
WebElement service = driver.findElement(By.xpath("//a[text()='Services']"));
Actions act = new Actions(driver);
act.moveToElement(service).perform();
List<WebElement> dropdown = driver.findElements(By.xpath("//li[@id='services']//ul//ul/li"));
System.out.println(dropdown.size());

FileWriter fileWriter = new FileWriter("D:\\seleniumworkspace\\SeleniumWebapplications\\src\\TestNG\\FilesforUpload\\abhi.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

for(WebElement ele: dropdown){
System.out.println(ele.getText());
bufferedWriter.write(ele.getText()+"\n");
}
bufferedWriter.close();

driver.close();
}
}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Wednesday, 27 August 2014

How can we enter a text without using SendKeys in Selenium Webdriver

We can enter a text in text box using SendKeys .but we can do this without using the send keys method also.


public class send{

public static void setattribute(WebElement element,String attributename,String Value){

WrapsDriver wrappedElement=(WrapsDriver)element;
JavascriptExecuter driver =(JavaScriptExecutor)wrappedElement.getWrapedDriver;
driver.executeScript(arguments[0].setAttribute(arguments[1],arguments[2]",element,
                                    attributeName,value);
}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

FrameWork


         is a set of automation guidelines which helps in:

1.Maintaining consistency of testing
2.Improves Test Structuring
3.Minimum usage of code
4.Improves re-usability
5.Non-technical testers can be involved in code
6.Involves data where-ever appropriate

Types :

1.DataDriven Framework
2.Method Driven Framework
3.Modular Driven FrameWork
4.Keyword Driven FrameWork
5.Hybrid(Combination of 1+2+3)

Different Components of your FrameWork

1.Library Assertion
2.Config Library
3.Generic Library
4.Project Specific Library
5.Modules
6.Driver Folders
7.Jars Folder
8.Excel Files


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

TestNg Annotations



1.@BeforeClass:The annotated method will be run before the first test method in the current class is invoked.
2.@BeforeMethod:The annotated method will be run before each test method.
3.@Test:The annotated method is a part of a test case.
4.@BeforeTest:The annotated method will be run before any test method belonging to the classes inside the tag is run.
5.@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
6.@AfterMethod:The annotated method will be run after each test method.
7.@AfterClass:The annotated method will be run after all the test methods in the current class have been run.
8.@BeforeSuite: The annotated method will be run before all tests in this suite have run.
9.@AfterSuite:The annotated method will be run after all tests in this suite have run.
10.@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
11.@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.
12.@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
13.@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Difference Between Qtp and Selenium

Major difference between QTP and Selenium are :

  • Selenium and QTP , both of them are automation testing tools.
  • Selenium is an open source tool while QTP is not an open source tool. It is owned by the HP.
  • Selenium is used to test only web based applications where as QTP can be used to test wide variety of applications like web based, .net based, Java based, mainframe applications.
  • Selenium supports scripting in many different languages like Java, .Net, Python, Ruby etc While in QTP only vb scripting is provided.
  • Web automation testing with selenium requires less cost as compared to automation using QTP due to license cost.


                FEATURES

              SELENIUM

                QTP

Cost

Open source & Portable

Licensed and very expensive.

Application support

Web Applications only

Client server applications only (like built in TCL/TK and PowerBuilder)

Support for web browsers

Supports IE, Firefox, Safari and Opera,Androidbrowser,chrome

Supports IE & Firefox only

Object Oriented Language support ,Scalability

Supports Java, .Net, Perl, PHP, Python, and Ruby

Supports VB script only

Support for operating system/platforms

Supports Windows ,PC/MAC/UNIX Platforms,Linux.

Support Windows only

Support for Test management tool integration

Not available. Need to track separately

TD/QC will be easily integrated

Environment Set Up Required

We can use wide range of IDEs like Eclipse, Netbeans, Visual Studio etc

Requires Seperate Environment

UI object management & Storage

Managed using UI-Element user extension and properties A set of dynamically loaded libraries that is stored in the Java archive file.

Built-in object repository and easy handling

DataDriven Testing


Requires Extensive coding

Complex VB Script Coding is required
Database support
Requires Extensive Coding
With the help of DSN (ODBC32 Interface)


How to Reverse a String using String Buffer and Without using string Buffer

package Test;

public class ReverseString {
public String reverseMyString(String str){
StringBuffer buffer = new StringBuffer(str);
buffer.reverse();
return buffer.toString();
}
public String reverseMyStringWithoutBuffer(String str){
int length = str.length();
String original = str;
String reverse = "";
for(int i = length-1; i>=0; i--){
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static void main(String[] args){

ReverseString rs = new ReverseString();
System.out.println("Reversed String using Buffer: "
                          +rs.reverseMyString("SeleniumWebdriver"));
System.out.println("Reversed String without Buffer: "
                           +rs.reverseMyStringWithoutBuffer("SeleniumWebDriver"));
}


}





To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

How to Delete all Cookies

package Testng;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Cookies {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.hdfcbank.com/");
        System.out.println("cookies before delete: "+driver.manage().getCookies());
        driver.manage().deleteAllCookies(); //
        System.out.println("cookies after delete: "+driver.manage().getCookies());
    }
}



To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

How to Open a link in a New tab

    To Open any hyperlink in a new tab we have to use actions objects.The required piece of code is given below.

package Testng;
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;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;

public class NewTab {
    public static void main(String[] args) {
       WebDriver driver = new FirefoxDriver();
        driver.get("http://www.hdfcbank.com/");
        driver.manage().window().maximize();
        Actions act = new Actions(driver);
        WebElement link = driver.findElement(By.linkText("Two Wheeler Loan"));
        act.moveToElement(link).contextClick().sendKeys("T").perform();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
         driver.close();
     
    }
}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Web Elements and Locators

  •  In WebDriver automation testing all about  related with web elements as it is an web application automation tool.
  • WebElement is nothing but, all DOM objects appeared in the web page. To perform the functions with DOM objects/ web elements  all we need to locate those elements exactly.


Syntax:

                WebElement element=driver.findElement(By.<Locator>);


  •    As we have seen in the above statement we want to specify some locator to identify the WebElement.


  • 'By' is the class, in that class we have different types of  static methods to identify elements. Those are,


  1. By.className
  2. By.cssSelector
  3. By.id
  4. By.linkText
  5. By.name
  6. By.partialLinkText
  7. By.tagName
  8. By.xpath 

1. By.className
See below example
Example:1
  <td class=name> </td>
WebElement td=driver.findElement(By.className("name"));

2.By.cssSelector
CSS selector is the one the best ways to locate some complex elements in the page.

See below some examples for easy understanding
Example:1
 <td class=name> </td>
driver.findElement(By.cssSelector("td.name"));     In css selector we can denote class name with dot (.)
                             (or)
driver.findElement(By.cssSelector("[class=name]"))    We can specify the attribute name and its value.


Example:2
<input id=create>
driver.findElement(By.cssSelector("#create")).sendKeys("test");    shortcut for denoting id is #
                                  ( or )
driver.findElement(By.cssSelector("[id=create]")).sendKeys("test")


Example:3
<td value=dynamicValue_13232><td>
driver.findElement(By.cssSelector("[value*=dynamicValue]"))     * is for checking contained value
(here value contains dynamicValue)


Example:4
          <div value=testing name=dynamic_2307></div>
driver.findElement(By.cssSelector("[value=testing][name*=dynamic]"));


If you want to include more attribute values in locator criteria use css locator as above.



3. By.id
See below example
Example:1
  <td id=newRecord> </td>
WebElement td=driver.findElement(By.id("newRecord"));


here we can specify the id attribute value directly.

4. By.linkText
See below example
Example:1
  <a onclick=gotonext()>Setup </a>
WebElement link=driver.findElement(By.linkText("Setup"));


This is the best locator for locating links (anchor tags) in your web page.

5. By.partialLinkText
See below example
Example:1
  <a onclick=gotonext()>very long link text </a>
WebElement link=driver.findElement(By.partialLinkText("very"));
                               (or)
WebElement link=driver.findElement(By.partialLinkText("long link"));


This is the locator for locating links (anchor tags) using partial text it contains .

6. By.name
See below example
Example:1
  <td name=WebDriver> </td>
WebElement td=driver.findElement(By.name("WebDriver"));

7. By.tagName
See below example
Example:1
  <td class=name> </td>
WebElement td=driver.findElement(By.tagName("td"));


If you want to get the entire text of web page use below logic.


driver.findElement(By.tagName("body")).getText();

8. By.xpath
                 Xpath is a really good way to navigate your site there are no IDS on elements that you need to work with or is near the element you want to work with.

(//): is used to search in entire structure

<html>
  <body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
 <input name="continue" type="submit" value="Login" />
 <input name="continue" type="button" value="Clear" />
 </form>
</body>
<html>
xpath=/html/body/form[1]  - Absolute path (would break if the HTML was changed only slightly)
//form[1] - First form element in the HTML
xpath=//form[@id='loginForm'] - The form element with attribute named ‘id’ and the value ‘loginForm


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

           




@DataProvider Annotation

               How to execute a test case with  multiple sets user inputs using  using the Robot objects.The beauty of Selenium Web Driver Automation provides two types. They are:
1.From Excel Sheet
2.@DataproviderAnnotation

    Both of them are having it's own Pro's and Con's.  I have provided the Sample code by using @Dataprovider Annotation .I will describe Writing and retrieving data from the Excel sheet in my next Post.


package TestNG;

import java.awt.AWTException;
import java.awt.Robot;
import java.util.concurrent.TimeUnit;
import junit.framework.AssertionFailedError;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginTestNg {

private WebDriver driver;

private String baseUrl;

private Robot robot;

@BeforeMethod

public void setUp() throws Exception {

driver =new FirefoxDriver();

baseUrl = "https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2&emr=1";

driver.manage().window().maximize();

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

System.out.println("@BeforeMethod - setUp");
}
////naming the inputs which  we can describe by Dataprovider Annotation
@DataProvider(name = "DP1")

public Object[][] createData() {

Object[][] retObjArr={{"abcdefgh","acdfe45l@"},                ///providing the inputs in which username and password required to login.

{" ","jjjfmfmldfi"},
                             
                                {"abishek","jksdhkhsdd"},

{" "," "},
                             
                                {"abhishekmucherla5",""}};

return(retObjArr);
}

/////////////naming the Dataprovider annotation in @test annotation

@Test (dataProvider = "DP1")

public void logiin(String username, String password) throws Exception{

driver.get(baseUrl + "/");

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


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

try {

robot = new Robot();

robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);


} catch (AWTException e) {

assert(e.getMessage().isEmpty()): AssertionFailedError.class.desiredAssertionStatus();

}

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

}
@AfterMethod

public void tearDown() throws Exception {

driver.quit();

System.out.println("@AfterMethod - tearDown");
}




To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

How a Tester to handle the Calendar Pop-Up or Date-Picker

Required Steps:

Click on the Calender button which shows calender image on the date which you want to select. 

Here in the below example, it will always select the current date , you can pass any date which you want to select as per your requirement. 


Package Testng:

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

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

    public class TodayDate {
    public static void main(String[] args) {
        int day, month, year;
          GregorianCalendar date = new GregorianCalendar();
          day = date.get(Calendar.DAY_OF_MONTH);
          month = date.get(Calendar.MONTH)+1;
          year = date.get(Calendar.YEAR);
          String today = "a_"+year+"_"+month+"_"+day;
          System.out.println(today);
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get("http://www.yatra.com/");
    driver.findElement(By.id("BE_flight_depart_date")).click();
    driver.findElement(By.xpath("//a[@id='"+today+"']")).click();
    driver.close();
    }

    }

Read an xml Testdata in Selenium

  We can create an element repository for storing the elements in xml,we have to retrieve those elements in the specified area.

Required steps:

Step 1: We have to create an xml and save in the definite location.
Step 2: We have to use attributes like <ElementReopository/>to save the elements.
Step 3: We have to use Document Builder methods to retrieve data from the xml .
Step 4: We have to name the path where the xml file has been saved.

Here  is the piece of code.

package HDFC;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.apache.commons.io.FileUtils;

import org.openqa.selenium.By;

public class Mainpage{

private WebDriver driver;
private static DocumentBuilder db;
private static Document doc;
private static NodeList nList;
private static File file;

public static String getFromhffc(String element) throws ParserConfigurationException, SAXException,

  IOException{

   try{

    file=new File("D:\\seleniumworkspace\\SeleniumWebapplications\\src\\TestNG\\XML\\hfc.xml");

    db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    doc = db.parse(file);

    nList = doc.getElementsByTagName(element);


   }catch(NullPointerException e){

    System.out.println("IOException in sssssss"+ e);
  }
  return nList.item(0).getTextContent();

  }
       public static void main(String[] args) {
             
               driver = new FirefoxDriver();
           
               driver.get("http://www.hdfcbank.com/");
           
               driver.findElement(By.className(getFromhffc("Logo"))).click();

        driver.findElement(By.linkText(getFromhffc("homme"))).click();

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

}
}

hfc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ElementRepository>
<Logo>logo</Logo>

<homme>Home</homme>
</ElementRepository>




To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Tuesday, 26 August 2014

How to capture Screenshot of Web Page in Selenium Webdriver

We know that capturing a screenshot is very important to a tester for validations ,As per the Automation testing in Selenium the java code required to capture a screenshot, To capture it the piece of code is given below.


package Spicejet;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;

public class FirstApplication{
private WebDriver driver;
File screenshot;

public void SpiceConnect() throws Exception {

                 driver = new FirefoxDriver();

// get the base url

driver.get("http://www.spicejet.com/");
             
                 //To maximize a window
                driver.manage().window().maximize();

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

//click on the link spice connect

driver.findElement(By.linkText("SpiceConnect")).click();

/// user registration login page screen shot

try {


screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(screenshot, new File("C:\\Users\\MY                                          PC\\Desktop\\Screenshots\\userregistration.png"));


}catch(Exception e){

System.out.println("Screen shot for registration page" + e);

}

driver.close();

}



To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Gmail Login Example with one user using Robot class objects

package TestNG;
import java.awt.AWTException;
import java.awt.Robot;
import java.util.concurrent.TimeUnit;

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

public class LoginTestNg {
private WebDriver driver;
private Robot robot;

public void login() throws Exception{
                    driver =new FirefoxDriver();
                    driver.get("https://accounts.google.com/ServiceLogin?                                  service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2&emr=1");

driver.findElement(By.id("Email")).sendKeys("abhishek5@gmail.com");

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

robot = new Robot();

robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);

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


}



To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

How to count number of letters,how many lines,and words in a text file the example is given below

package TestNG;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileCount
{

public static void main(String[] args) throws FileNotFoundException
{
Scanner reader;
reader = new Scanner(new FileInputStream("D:\\seleniumworkspace\\SeleniumWebapplications\\src\\TestNG\\FilesforUpload\\kk.txt"));
int w=0,c=0,l=0;
while(reader.hasNextLine())
{
l++;
reader.nextLine();
}
reader.close();
reader = new Scanner(new FileInputStream("D:\\seleniumworkspace\\SeleniumWebapplications\\src\\TestNG\\FilesforUpload\\kk.txt"));
while(reader.hasNext())
{
String s=reader.next();
w++;
c=c+s.length();
}

while(reader.hasNextLine())
{
l++;
reader.nextLine();
}
reader.close();
System.out.println("Word:"+w);
System.out.println("Chr:"+c);
System.out.println("Lines:"+l);
}

}



To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Windows Scroll down the Taskbar Example

In a web page the scroll down of the page should be done automatically.The example is given below.

package TestNG;

import java.util.concurrent.TimeUnit;

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

public class scrolldown {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.flipkart.com/womens-clothing/pr?sid=2oq%2Cc1r...");
driver.manage().window().maximize();
JavascriptExecutor jsx = (JavascriptExecutor)driver;
jsx.executeScript("window.scrollBy(0,4500)", "");
Thread.sleep(3000);
driver.close();
}
}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Capatcha Example

 How can we  automate to capture a text from capatcha and print the value in textbox to submit verification.  the example is given below.

package TestNG;

import java.util.concurrent.TimeUnit;

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

public class Capatcha {

public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.indianrail.gov.in/pnr_Enq.html");
        String captchaValue = driver.findElement(By.xpath("//span[@id='txtCaptchaDiv']")).getText();  //this will read the captcha
        System.out.println(captchaValue);
        driver.findElement(By.xpath("//input[@id='txtInput']")).sendKeys(captchaValue);
        driver.findElement(By.name("submit")).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

How to clear the text on Google Search box when it is entered the text in it?

package TestNG;

import java.util.Scanner;

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;

public class Clear {

public static void main(String[] args) throws InterruptedException {
       Scanner in = new Scanner(System.in);
       System.out.println("enter the string which you want to send and then clean");
       String input = in.next();
       WebDriver driver = new FirefoxDriver();
       driver.get("https://www.google.co.in/?       gfe_rd=cr&ei=zQmQU9D3OoyK8QfpxoDQBA&gws_rd=ssl");
       WebElement box = driver.findElement(By.name("q"));
       box.sendKeys(input);
       Thread.sleep(5000); //simply wait to see that input string has been sent to box
     
       //this for block is used to clear the input from box
       //this we can do by using clear method but clear sometime won't work so use this way
       //box.clear();
       box.sendKeys(Keys.chord(Keys.CONTROL,"a"));
     
       box.sendKeys(Keys.BACK_SPACE);
     
   }


}


To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere

Selenium WebDriver Archietecure

Selenium is a browser automation tool, commonly used to test web applications. It will automate the control of a browser so that repetitive tasks can be automated. At a very high level, Selenium is a suite of three tools.
Selenium IDE is an extension for Firefox that allows users to record and playback tests.
Selenium WebDriver, provides APIs in a variety of languages to allow for more control and the application of standard software development practices. 
Selenium Grid makes it possible to use the Selenium APIs to control browser instances distributed over a grid of machines, allowing more tests to run in parallel.
In this article let’s see the Architecture of Selenium WebDriver.
Selenium WebDriver:
Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation. Since there are so many browsers & so many programming languages there is need for common specification which will be provided by WebDriver API. Each browser has to implement this API which is called as Remote WebDriver or Remote WebDriver Server. At a higher level Selenium WebDriver architecture look like this.

The language bindings will send the commands across the common driver API, on the other end there is going to be a driver listening to those commands and they will be executed in browser using remote WebDriver and it’s going to return the result/response via API to the code/Binding.
All implementations of WebDriver API that communicates with the browser (which is called as a Remote WebDriver) shall use a common wire protocol which is named as JSON Wired Protocol which is a RESTFUL webservice using JSON over HTTP.


Actually whatever the commands issued in the code will be interpreted into Webservice methods (HTTP methods to a specified URL) and the Remote Driver will receive the HTTP request (commands) and the execute them in the browser then send the response back.



To know FAQ's on Selenium Please ClickHere
To know SQL's Queries Required For Testers Please ClickHere