Automation Using Selenium Webdriver

Tuesday 13 September 2016

TestNG Examples

It explains the order of the methods called. Here is the execution procedure of the TestNG test API methods with an example.

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;

public class TestngAnnotation {
   // test case 1
   @Test
   public void testCase1() {
      System.out.println("in test case 1");
   }

   // test case 2
   @Test
   public void testCase2() {
      System.out.println("in test case 2");
   }

   @BeforeMethod
   public void beforeMethod() {
      System.out.println("in beforeMethod");
   }

   @AfterMethod
   public void afterMethod() {
      System.out.println("in afterMethod");
   }

   @BeforeClass
   public void beforeClass() {
      System.out.println("in beforeClass");
   }

   @AfterClass
   public void afterClass() {
      System.out.println("in afterClass");
   }

   @BeforeTest
   public void beforeTest() {
      System.out.println("in beforeTest");
   }

   @AfterTest
   public void afterTest() {
      System.out.println("in afterTest");
   }

   @BeforeSuite
   public void beforeSuite() {
      System.out.println("in beforeSuite");
   }

   @AfterSuite
   public void afterSuite() {
      System.out.println("in afterSuite");
  
xml version<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite1">
  <test name="test1">
    <classes>
       <class name="TestngAnnotation"/>
    </classes>
  </test>
</suite>
output:
in beforeSuite
in beforeTest
in beforeClass
in beforeMethod
in test case 1
in afterMethod
in beforeMethod
in test case 2
in afterMethod
in afterClass
in afterTest
in afterSuite

===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
Based on the above output, the execution procedure is as follows:
  • First of all, beforeSuite() method is executed only once.
  • Lastly, the afterSuite() method executes only once.
  • Even the methods beforeTest(), beforeClass(), afterClass(), and afterTest() methods are executed only once.
  • beforeMethod() method executes for each test case but before executing the test case.
  • afterMethod() method executes for each test case but after executing the test case.
  • In between beforeMethod() and afterMethod(), each test case executes.

Wednesday 7 September 2016

Java programs

Palindrome number algorithm

  • Get the number to check for palindrome
  • Hold the number in temporary variable
  • Reverse the number
  • Compare the temporary number with reversed number
  • If both numbers are same, print "palindrome number"
  • Else print "not palindrome number"
  • class PalindromeExample{  
  •  public static void main(String args[]){  
  •   int r,sum=0,temp;    
  •   int n=454;//It is the number variable to be checked for palindrome  
  •   
  •   temp=n;    
  •   while(n>0){    
  •    r=n%10;  //getting remainder  
  •    sum=(sum*10)+r;    
  •    n=n/10;    
  •   }    
  •   if(temp==sum)    
  •    System.out.println("palindrome number ");    
  •   else    
  •    System.out.println("not palindrome");    
  • }  
  • }  
  • out put:
  • palindrome  number

Factorial Program using loop in java

  1. class FactorialExample{  
  2.  public static void main(String args[]){  
  3.   int i,fact=1;  
  4.   int number=5;//It is the number to calculate factorial    
  5.   for(i=1;i<=number;i++){    
  6.       fact=fact*i;    
  7.   }    
  8.   System.out.println("Factorial of "+number+" is: "+fact);    
  9.  }  
  10. }  
  11. out put:Factorial of 5 is: 120

Prime Number Program in Java

Prime number in Java: Prime number is a number that is greater than 1 and divided 
by 1 or itself. In other words, prime numbers can't be divided by other 
numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.

  1. class PrimeExample{  
  2.  public static void main(String args[]){  
  3.   int i,m=0,flag=0;    
  4.   int n=17;//it is the number to be checked  
  5.   m=n/2;    
  6.   for(i=2;i<=m;i++){    
  7.    if(n%i==0){    
  8.    System.out.println("Number is not prime");    
  9.    flag=1;    
  10.    break;    
  11.    }    
  12.   }    
  13.   if(flag==0)    
  14.   System.out.println("Number is prime");    
  15. }  
  16. }  
  17. Output:Number is prime

Armstrong Number in Java: Armstrong number is a number that is equal
 to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.
Let's try to understand why 153 is an Armstrong number.

  1. 153 = (1*1*1)+(5*5*5)+(3*3*3)  
  2. where:  
  3. (1*1*1)=1  
  4. (5*5*5)=125  
  5. (3*3*3)=27  
  6. So:  
  7. 1+125+27=153

  1. class ArmstrongExample{  
  2.   public static void main(String[] args)  {  
  3.     int c=0,a,temp;  
  4.     int n=153;//It is the number to check armstrong  
  5.     temp=n;  
  6.     while(n>0)  
  7.     {  
  8.     a=n%10;  
  9.     n=n/10;  
  10.     c=c+(a*a*a);  
  11.     }  
  12.     if(temp==c)  
  13.     System.out.println("armstrong number");   
  14.     else  
  15.         System.out.println("Not armstrong number");   
  16.    }  


Compare String with/without using equals() method.



mport java.util.Scanner;

public class CompareString{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the 1st String: ");
        String s1 = in.next();
        System.out.println("Enter the 2nd String: ");
        String s2 = in.next();

        //1st approach without using equals() method
        System.out.println("*********compare  1st String ************");
        if(s1.length()==s2.length()){
            for(int i=0; i<s1.length(); i++){
                if(s1.charAt(i)!=s2.charAt(i)){
                    System.out.println("String "+s1+" is not equal to string "+s2);
                    break;
                }
            }
            System.out.println("String "+s1+" is equal to string "+s2);
        }else{
            System.out.println("String "+s1+" is not equal to string "+s2);
        }

        //2nd approach , just use equals() method
        System.out.println("*********compare 2nd String************");
        if(s1.equals(s2)){
            System.out.println("String "+s1+" is equal to string "+s2);
        }else{
            System.out.println("String "+s1+" is not equal to string "+s2);
        }    
    }
}
OutPut
-------------

Enter the 1st String: 
Selenium Webdriver
Enter the 2nd String: 
Selenium Webdriver
*********compare  1st String************
String Selenium Webdriver is equal to string Selenium Webdriver
*********compare  2nd String************
String Selenium Webdriver is equal to string Selenium Webdriver

Flyod Trinagle


Note- Floyd Triangle is like
1
2 3
4 5 6
7 8 9 10
------------
Code-

import java.util.Scanner;

public class FloydTriangle{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
        int r = in.nextInt();
        int n=0;
        for(int i=0; i<r; i++){
            for(int j=0; j<=i; j++){
                System.out.print(++n+" ");
            }
            System.out.println();
        }
    }
}

Output

Enter the number of rows which you want in your Floyd Triangle: 
5

2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

Thursday 11 August 2016

Selenium Faqs

1.What are the annotations used in TestNG ?

Ans:@Test, @BeforeSuite, @AfterSuite, @BeforeTest,
@AfterTest, @BeforeClass, @AfterClass, @BeforeMethod,
 @AfterMethod.

2.How do you read data from excel ?

Ans:
1.FileInputStreamfis = new FileInputStream(“path of excel file”);


2.Workbook wb = WorkbookFactory.create(fis);



3.Sheet s = wb.getSheet(“sheetName”);



4.String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue();

3.What is the use of xpath ?

Ans:it is used to find the WebElement in web page.
It is very useful to identify the dynamic web elements.

4.What are different types of locators ?

Ans:There are 8 types of locators and all are the static methods of
 the By class.By.id(), By.name(), By.tagName(), By.className(),
By.linkText(), By.partialLinkText(), By.xpath, By.cssSelector().

5.What is the difference between Assert and Verify?

Ans: Assert- it is used to verify the result. If the test case fail then
 it will stop the execution of the test case there itself and move
 the control to other test case.
Verify- it is also used to verify the result. If the test case fail then
 it will not stop the execution of that test case.

6.What is the alternate way to click on login button?

Ans:use submit() method but it can be used only when attribute
type=submit.

7.How do you verify if the checkbox/radio is checked or not ?

Ans:We can use isSelected() method.
Syntax –

1.driver.findElement(By.xpath(“xpath of the checkbox/radio button”)).isSelected();
If the return value of this method is true then it is checked else it is not.

8.How do you handle alert pop-up ?

Ans:To handle alert pop-ups, we need to 1st switch control to
 alert pop-ups then click on ok or cancle then move control back to
 main page.
String mainPage = driver.getWindowHandle();
Alert alt = driver.switchTo().alert(); // to move control to alert popup
alt.accept(); // to click on ok.
alt.dismiss(); // to click on cancel.

//Then move the control back to main web page-

driver.switchTo().window(mainPage); → to switch back to main page.

9. How do you launch IE/chrome browser?

Ans: Before launching IE or Chrome browser we need to set the System property.

//To open IE browser


System.setProperty(“webdriver.ie.driver”,”path of the iedriver.exe file ”);



WebDriver driver = new InternetExplorerDriver();


4 //To open Chrome browser →
 System.setProperty(“webdriver.chrome.driver”,”path of the chromeDriver.exe file ”);
5 WebDriver driver = new ChromeDriver();

10.How to perform right click using WebDriver?

Ans:Use Actions class

 1. Actions act = new Actions(driver);
2 .// where driver is WebDriver type

3. act.moveToElement(webElement).perform();

4. act.contextClick().perform();

11.How do perform drag and drop using WebDriver?

Ans:Use Action class

 1. Actions act = new Actions(driver);


2. WebElement source = driver.findElement(By.xpath(“ —–”));

//source ele whichyou want to drag

3.WebElement target = driver.findElement(By.xpath(“ —–”));
//target where you want to drop

4. act.dragAndDrop(source,target).perform();


12.Give the example for method overload in WebDriver.

Ans:Frame(string), frame(int), frame(WebElement).

13.How do you upload a file?

Ans: To upload a file we can use sendKeys() method.

1 driver.findElement(By.xpath(“input field”)).sendKeys(“path of the file which u want to upload”);

14.How do you click on a menu item in a drop down menu?

Ans:If that menu has been created by using select tag then we can use the methods
selectByValue() or selectByIndex() or selectByVisibleText().
These are the methods of the Select class.
If the menu has not been created by using the select tag then we can
 simply find the xpath of that element and click on that to select.

15.How do you simulate browser back and forward ?

Ans:

 1driver.navigate().back();


2 driver.navigate().forward();

16.How do you get the current page URL ?

Ans:
1 driver.getCurrentUrl();

17.What is the difference between ‘/’ and ‘//’ ?

Ans://- it is used to search in the entire structure.
/- it is used to identify the immediate child.

18.What is the difference between findElement and findElements?

Ans:Both methods are abstract method of WebDriver interface and used to
 find the WebElement in a web page.

findElement() – it used to find the one web element. It return only one WebElement type.

findElements()- it used to find more than one web element. It return List of WebElements.

19.How do you achieve synchronization in WebDriver ?

Ans:We can use implicit wait.
Syntax- driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Here it will wait for 10sec if while execution driver did not find
the element in the page immediately.
This code will attach with each and every line of the script automatically.
It is not required to write every time. Just write it once after opening the browser.

20.Write the code for Reading and Writing to Excel through Selenium ?

Ans:1.FileInputStreamfis = new FileInputStream(“path of excel file”);

2. Workbook wb = WorkbookFactory.create(fis);

3. Sheet s = wb.getSheet(“sheetName”);

4. String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue(); // read data

5. s.getRow(rowNum).getCell(cellNum).setCellValue(“value to be set”); //write data

6.FileOutputStreamfos = new FileOutputStream(“path of file”);

7.wb.write(fos); //save file

21.How to get typed text from a textbox ?

Ans:use getAttribute(“value”) method by passing arg as value.

1 String typedText = driver.findElement(By.xpath(“xpath of box”)).getAttribute(“value”));

22.What are the different exceptions you got when working with WebDriver ?

Ans:ElementNotVisibleException, ElementNotSelectableException, NoAlertPresentException,
 NoSuchAttributeException, NoSuchWindowException, TimeoutException, WebDriverException etc.

23.What are the languages supported by WebDriver ?

Ans:Python, Ruby, C# and Java are all supported directly by the development team.
There are also webdriver implementations for PHP and Perl.

24.How do you clear the contents of a textbox in selenium ?

Ans:Use clear() method.

1.driver.findElement(By.xpath(“xpath of box”)).clear();

25.What is a Framework ?
Ans:A framework is set of automation guidelines which help in
Maintaining consistency of Testing, Improves test structuring, Minimum usage of code, Less Maintenance of code, Improve re-usability, Non Technical testers can be involved in code, Training period of using the tool can be reduced, Involves Data wherever appropriate.
There are five types of framework used in software automation testing:
1-Data Driven Automation Framework
2-Method Driven Automation Framework
3-Modular Automation Framework
4-Keyword Driven Automation Framework
5-Hybrid Automation Framework ,its basically combination of different frameworks. (1+2+3).

26.What are the prerequisites to run selenium webdriver?

Ans:JDK, Eclipse, WebDriver(selenium standalone jar file), browser, application to be tested.

27.What are the advantages of selenium webdriver?

Ans:It supports with most of the browsers like Firefox, IE, Chrome, Safari, Opera etc.

a) It supports with most of the language like Java, Python, Ruby, C# etc.
b) Doesn’t require to start server before executing the test script.
c) It has actual core API which has binding in a range of languages.
d) It supports of moving mouse cursors.
e) It support to test iphone/Android applications.
28.What is WebDriverBackedSelenium ?

Ans:WebDriverBackedSelenium is a kind of class name where we can create an object for it as below:

Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, “URL path of website”)
The main use of this is when we want to write code using both WebDriver and Selenium RC , we must use above created object to use selenium commands.

29.How to invoke an application in webdriver ?

Ans:
  driver.get(“url”); or driver.navigate().to(“url”);