Automation Using Selenium Webdriver

Tuesday, 24 January 2017

Closing All Tabs Using Robot Class In Selenium WebDriver

Closing All Tabs Using Robot Class In Selenium WebDriver

Earlier we have used java robot class to save Image from page In THIS POST. Robot class Is useful to send key-press and key-release events. We will use same thing here to perform keyboard ALT + SPACE + "c" (Shortcut key)  key-press events to close all tabs of browser. We can perform this key-press event sequence very easily using Robot class. I am suggesting you to use always WebDriver's driver.quit(); method to close all tabs of browser. Intention of this postIs to make you more aware about Robot class usage with selenium WebDriver so you can perform such tricky actions 
easily whenever required.

Bellow given example has used Robot class In @AfterTest methodto close browser tabs using ALT + SPACE + 'c' key-press event sequence. Run It In your eclipse IDE to check how It works.


package Testing_Pack;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
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.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Tabs {

 WebDriver driver;
 Robot rb;

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

 @Test
 public void openTab() {  
  driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
  driver.get("http:try your own");
  switchToTab();
  driver.findElement(By.xpath("//input[@id='6']")).click();
  driver.findElement(By.xpath("//input[@id='plus']"));
  driver.findElement(By.xpath("//input[@id='3']"));
  driver.findElement(By.xpath("//input[@id='equals']"));
  
  switchToTab();
  driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("hi");
  driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("test");
  
  switchToTab();
  String str = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
  System.out.println("Sum result Is -> "+str);
 } 

 public void switchToTab() {  
  driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");  
  driver.switchTo().defaultContent();  
 }

 @AfterTest
 public void closeTabs() throws AWTException {
  //Used Robot class to perform ALT + SPACE + 'c' keypress event.
  rb =new Robot();
  rb.keyPress(KeyEvent.VK_ALT);
  rb.keyPress(KeyEvent.VK_SPACE);
  rb.keyPress(KeyEvent.VK_C);
 }
}

Monday, 23 January 2017

Difference between Collections and Collection in java with example program

Difference between Collections and Collection in java with example program

Famous java interview question: difference between collections and collection in java
Major difference between Collection and Collections is Collection is an interface and Collections is a class.
Both are belongs to java.util package
Collection is base interface for list set and queue.
Collections is a class and it is called utility class.
Collections utility class contains some predefined methods so that we can use while working with
Collection type of classes(treeset, arraylist, linkedlist etc.)
Collection is base interface for List , Set and Queue.


Collection vs Collections

public interface Collection<E>
extends Iterable<E>


public class Collections
extends Object

Collections utility class contains static utility methods so that we can use those methods by using
class name without creating object of Collections class object
Lest see some methods of Collections class.


addAll: public static <T> boolean addAll(Collection<? super T> c,T... elements)
reverseOrder: public static <T> Comparator<T> reverseOrder()
shuffle: public static void shuffle(List<?> list)
sort:public static <T extends Comparable<? super T>> void sort(List<T> list)
How to Relate Collection and Collections
ArrayList is a Collection type of class means it is implementing Collection interface internally
Now lets see a java example program to sort ArrayList of elements using Collections.sort() method.

public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable


1.Basic Java example program to sort arraylist of integers using Collections.sort() method

package com.javasortarraylistofobjects;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class SortArrayListExample{

public static void main(String[] args) {

//create an ArrayList object
 ArrayList<Integer> arrayList = new ArrayList<Integer>();
     
 //Add elements to Arraylist
arrayList.add(10);
arrayList.add(7);
arrayList.add(11);
arrayList.add(4);
arrayList.add(9);
arrayList.add(6);
arrayList.add(2);
arrayList.add(8);
arrayList.add(5);
arrayList.add(1);
     
     
 System.out.println("Before sorting ArrayList ...");
 Iterator itr=arrayList.iterator();
     
while (itr.hasNext()) {

System.out.println(itr.next());
   
}

     
 /*
 To sort an ArrayList object, use Collection.sort method. This is a
  static method. It sorts an ArrayList object's elements into ascending order.
*/
  Collections.sort(arrayList);
   
  System.out.println("After sorting ArrayList ...");
     
 
     
Iterator itr1=arrayList.iterator();
     
while (itr1.hasNext()) {

System.out.println(itr1.next());
         
}
 

}
}



Output:

Before sorting ArrayList ...
10
7
11
4
9
6
2
8
5
1
After sorting ArrayList ...
1
2
4
5
6
7
8
9
10
11

Wednesday, 4 January 2017

How to Automate Radio button and Checkbox in Selenium webdriver

How to Automate Radio button and Checkbox in Selenium webdriver


                      HTML For Checkbox



                   <input type=”checkbox”>

                     For Radio Button

                    <input type=”radio”>

Automate radio button and checkbox in selenium
When you inspect these elements via firebug and firepath you will get above html type.

The main difference between radio button and checkbox is checkbox you can select multiple but for radio button, only one selection is possible.

In Selenium we have 1 method called click() to perform click events.

This click() method you can apply with radio button, checkbox, links and sometime with dropdown as well.

Let us get started

Demo Code


WebElement ele=driver.findElement(By.id());
ele.click();

WebElement ele=driver.findElement(By.id());
ele.click();

In this example I have used id only but if you want to make you script stable then you should use Xpath and CSS in your script.

Before performing click action, sometimes we need to verify some activity as well, take some example

You need to verify whether radio button or checkbox is enabled.
You need to verify whether radio button or checkbox is Displayed on UI or not.
You need to verify whether checkbox and radio button is default selected or not.
Above validations are must used in script because automation is all about validation only. You will get these type of questions in interviews also.

These words looks quite big while listening but we can easily verify this using some predefined method in Selenium.

These methods are


isDisplayed();

isEnabled();

isSelected();

isSelected();
Therefore, you must be eager now how to use these methods in script so let us see these methods using a single program.



Program to Automate radio button and checkbox in selenium

 import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FacebookDropdown {

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

          WebDriver driver=new FirefoxDriver();

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

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

         WebElement male_radio_button=driver.findElement(By.id("u_0_e"));

         boolean status=male_radio_button.isDisplayed();

         System.out.println("Male radio button is Displayed >>"+status);

          boolean enabled_status=male_radio_button.isEnabled();

          System.out.println("Male radio button is Enabled >>"+enabled_status);

        boolean selected_status=male_radio_button.isSelected();

          System.out.println("Male radio button is Selected >>"+selected_status);

          male_radio_button.click();

        boolean selected_status_new=male_radio_button.isSelected();

          System.out.println("Male radio button is Selected >>"+selected_status_new);

     }

}


 import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FacebookDropdown {

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

          WebDriver driver=new FirefoxDriver();

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

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

         WebElement male_radio_button=driver.findElement(By.id("u_0_e"));

         boolean status=male_radio_button.isDisplayed();

         System.out.println("Male radio button is Displayed >>"+status);

          boolean enabled_status=male_radio_button.isEnabled();

          System.out.println("Male radio button is Enabled >>"+enabled_status);

        boolean selected_status=male_radio_button.isSelected();

          System.out.println("Male radio button is Selected >>"+selected_status);

          male_radio_button.click();

        boolean selected_status_new=male_radio_button.isSelected();

          System.out.println("Male radio button is Selected >>"+selected_status_new);

     }

}
 Explanation- If you notice above scenario before click Selected status was false but after click status changed to TRUE.

Output:
Male radio button is display>>>true
Male radio button is Enable>>true
Male radio button is selected>>false
Click on radio button
Male radio button is selected>>True


     

Thursday, 29 December 2016

Java Program to Sort elements of Java ArrayList Example


1.Basic Java example program to sort arraylist of integers

  1. package com.javasortarraylistofobjects;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class SortArrayList{
  8.  
  9. public static void main(String[] args) {
  10.   
  11. //create an ArrayList object
  12.  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  13.        
  14.  //Add elements to Arraylist
  15. arrayList.add(10);
  16. arrayList.add(7);
  17. arrayList.add(11);
  18. arrayList.add(4);
  19. arrayList.add(9);
  20. arrayList.add(6);
  21. arrayList.add(2);
  22. arrayList.add(8);
  23. arrayList.add(5);
  24. arrayList.add(1);
  25.         
  26.         
  27.  System.out.println("Before sorting ArrayList ...");
  28.  Iterator itr=arrayList.iterator();
  29.         
  30. while (itr.hasNext()) {
  31.  
  32. System.out.println(itr.next());
  33.      
  34. }
  35.  
  36.        
  37.  /*
  38.  To sort an ArrayList object, use Collection.sort method. This is a
  39.   static method. It sorts an ArrayList object's elements into ascending order.
  40. */
  41.   Collections.sort(arrayList);
  42.      
  43.   System.out.println("After sorting ArrayList ...");
  44.        
  45.     
  46.         
  47. Iterator itr1=arrayList.iterator();
  48.         
  49. while (itr1.hasNext()) {

  50. System.out.println(itr1.next());
  51.             
  52. }
  53.     
  54.   
  55. }
  56. }



OUTPUT::
  1. Before sorting ArrayList ...
  2. 10
  3. 7
  4. 11
  5. 4
  6. 9
  7. 6
  8. 2
  9. 8
  10. 5
  11. 1
  12. After sorting ArrayList ...
  13. 1
  14. 2
  15. 4
  16. 5
  17. 6
  18. 7
  19. 8
  20. 9
  21. 10
  22. 11

Wednesday, 28 December 2016

TCS selenium webdriver interview questions 2nd Dec

---------------    ************   ---------------- *********      -------------------------


  Introduce yourself  tell something about your last project?
  Count no. Of words and sentence in notepad and arrange them in ascending order?
  Write the format of XML file for BATCH EXICUTION?

  Please explain your project architecture with framework with diagram?
  What  are  the technical challanges you have faced?
. there are one string say Aattribute , so write a code to find the repeated word in that string 
  and it should work for case insensitive(work for lower case and upper case) ?
  Write a query for self join?
  how to take screenshot write code?
. if you have opened any web application and it is broken means it has changed its layout and other         thing which type of testing you will perform to check this?
   What are the things u stored in PageFactory ? Why ?
  Explain TestNG?
  What are the annotations U have Used and why ?
  Explain Agile Method?
  What is StringBuffer and StringBuilder?
  Difference between delete and truncate ?















Tuesday, 27 December 2016

Collections Set in Java

Collections:
  • Collections in java is a framework that provides an architecture to store and display the data.
  • Collections API provides interfaces and classes.
  • Using Collection we can perform operations like searching,sorting,insertion,deletion,manipulation.
  • Collections is nothing but group of different type of objects together as a single entity is also known as Collections.
  • Collections are growable Nature.
  • Collection Framework having Interfaces like Set,List,Map.Every Interface having classes.
Why Collection Came?
  • Arrays are fixed in size.we can't increase size of Arrays.that's y only collections came.collections having growable nature.we can increase size.
Set Interface:
  • A set is a collection that having only unique elements.Duplicate won't be there.
  • Set having no index.
  • Set allows only one null value.
  • Set having classes like :
  • HashSet
  • LinkedHashMap
  • TreeSet

HashSet:

HashSet having only unique elements.
HashSet having no Order.
HashSet allows only one null value.

Program for HashSet:
package.com.instanceofjava;
import.java.util.HashSet;

public class A{
public static void main(String args[]){

HashSet hashset=new HashSet();

hashset.add("Indhu");
hashset.add("Indhu");
hashset.add("Sindhu");
hashset.add("swathi");
hashset.add(null);
hashset.add(null);
hashset.add("Lavs");
Iterator it=hashset.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
}
}
Output:
Indhu
null
Lavs
Sindhu
swathi

LinkedHashMap:
  • LinkedHashMap allows only unique elements.
  • LinkedHasMap allows Insertion order.
  • LinkedHashMap allows only one null value.

Program for LinkedHashSet;

package.com.instanceofjava;
import.java.util.LinkedHashSet;

public class testSet{
public static void main(String args[]){

LinkedHasMap linkedHashMap=new LinkedHasMap();

linkedHashMap.add("Indhu');
linkedHashMap.add("Indhu");
linkedHashMap.add("Sindhu");
linkedHashMap.add("Bindhu");
linkedHashMap.add(null);
linkedHashMap.add(null);

Iterator it=linkedHashMap.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
}
}

Output:
Indhu
Sindhu
Bindhu
null


TreeSet:
  • TreeSet Allows only Unique elements.
  • Treeset having sorted order
  • TreeSet doesn't allow  any null value.
Program for TreeSet:

package.com.instanceofjava;
import.java.util.TreeSet;

Public class testSet2{

public static void main(String args[]){
TreeSet treeSet=new treeSet();
treeSet.add("Sindhu");
treeSet.add("Sindhu");
treeSet.add("Indhu");
treeSet.add("Bindhu');
Iterator it=treeSet.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
}
}

Output:
Bindhu
Indhu
Sindhu
  • in Set interface if you want to add elements you can use add() method.
  • If you want to remove you can use remove() method.

Monday, 26 December 2016

String vs stringbuffer vs stringbuilder

1.Definition:

  • String is an immutable sequence of characters.
  • StringBuffer is mutable sequence of characters.
  • StringBuilder is also mutable sequence of characters.

The only difference between StringBuffer and StringBuilder: 

  • StringBuffer object is thread safe , it means StringBuffer object is modified by multiple concurrently, because  all its methods are declared as "synchronized".
  • StringBuilder class is given in jdk 1.5 version as non thread -safe class, means all its methods are non synchronized methods.
  • So , in single model application we must use StringBuilder, so that object locking and unlocking will not be there, hence performance is increased.
  • In single thread model application operations are executed in sequence hence there is no chance of object corruption.

When should we choose String and StringBuffer? 

  • If we do not want to store string modifications in the same memory we must choose String.
  • To do modifications in the same memory, we must choose StringBuffer or StringBuilder.

 Advantage and disadvantage in String: 

  • Advantage : Since modifications are preserving in another memory location, we will have both original and modified values.
  • Disadvantage: It consumes lot memory for every operation, as it stores it modifications in new memory. So it leads to performance issue.
  • Solution: To solve this performance issue , in projects developers store string data using StringBuilder or StringBuffer after all modifications they convert into String and pass it back to user.

Advantage and disadvantage of StringBuffer or StringBuilder:

  • Advantage: It given high performance because consumes less memory as all modifications stored in same memory.
  • Disadvantage: Original value will not be preserved.

2.Creating String , StringBuffer objects: 

String:

  • String object can be created in two ways.
  • By using string literal : String str="instance of java ";
  • By using its constructors: String str= new String("instaneofjavaforus") ;

StringBuffer:

  • By using its available constructors
  • StringBuffer str= new StringBuffer();

StringBuilder:

  • By using its available constructors
  • StringBuilder str= new StringBuilder ();

3.Special operations those we can only perform on StringBuffer and StringBuilder: 

  1. append
  2. insert
  3. delete
  4. reverse
  •  Since string is immutable we cannot perform these operations on String.

4.Concatenation:

  • Using String object we can concat new string to the current  string in two ways.
  1. Using + operator
  2. using concat() method.
  • Using StringBuffer we can perform concat operation only in one way
  1. Using append() method
  • Using StringBuilder we can perform concat operation only in one way
  1. Using append() method
package com.javaforus;
public Class SBDemo{ 
public static void main (String args[]) {
        String str="Java";
        StringBuffer sb= new StringBuffer("Java");
        StringBuilder sbr= new StringBuilder("Java");
       System.out.println(str.concat(" language"));    
       System.out.println(sb.append(" language"));
        System.out.println(sbr.append(" language"));
}
}
OutPut:
Java language
Java language
Java language

5.Comparison:

  • Using equals() method String objects are compared with state, because it is overridden in this class. Also hashcode(0 method is overridden in order to satisfy equals() method contract.
  • But in StringBuffer and in StringBuilder equals() method is not overridden , so using equals() method their object are compared with reference.