Selenium and Java

Wednesday, 24 June 2015

Java- Static Keyword

Java- Static Keyword


The static keyword can be used in 3 scenarios:

  • static variables
  • static methods
  • static blocks of code

1. Static Variable :

When a variable is declared with the keyword “static”, its called a “class variable”. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create a instance.

Without the “static” keyword, it’s called instance variable, and each instance of the class has its own copy of the variable.

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<variable-name>
















2. Static Method:

Any method defined as Static can be called without creating an object of class. The best example is main method , as at the start of execution no object created so main method is defined as Static.A
static method belongs to class rather than an object of the class

Calling Static Methods

Invoke static methods using the name of the class followed by dot (.), then the name of the method:
classname.staticMethodName(args,...)

There are two main restrictions for the static method. They are:
  1. The static method can not use non static data member or call non-static method directly.
  2. this and super cannot be used in static context.

Tuesday, 23 June 2015

Java- Encapsulation


Encapsulation :

To define what level of information share with other word in Java is called Encapsulation. Access restriction level is achieved by Access modifiers (Privet, Public, Package, Protected), These are 4 Ps of Object oriented program .Encapsulation in java is a process of wrapping code and data together into a single unit.

Access Modifiers :

Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.
Four access modifier available in Java as Package Privet, Protected, Public.
Package access modifier is default access modifier, that means if we don't use any access modifier then Package level restriction will be applied.
Public Access modifier is the least restrictive where as Privet is most restrictive.
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.


Modifier Class Package Subclass World
PublicYYYY
ProtectedYYYN
PackageYYNN
PrivateNYNN


1. Public Access Modifier:

Public access modifier is least restrictive and class ,method ,interface and variables with this access modifier are accessible from any class in Java.

However if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its sub classes.




2. Package Access Modifier (default):

If we don't use any access modifiers than Default access modifier Package is considered by default. In this case class ,method and variable will be access withing same package. we can not use class, method and variable defined as package or no access modifiers outside package.






3. Protected Access Modifier :

The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.




4. Privet Access Modifier :

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Monday, 8 June 2015

Java- Polymorphism

Polymorphism : 

Polymorphism is the ability of an object to take on many forms.
The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object (inheritance).

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism (overloading) and runtime polymorphism (overriding). We can perform polymorphism in java by method overloading and method overriding.

public class Animal{} public class Deer extends Animal {}

Overloading Method : 

Overloading is determined at the compile time. It occurs when several methods have same names with:

      a. Different method signature and different number or type of parameters.
      b.Same method signature but different number of parameters.
      c.Same method signature and same number of parameters but of different type

Overriding Method : 

Overriding occurs when a class method has the same name and signature as a method in parent class. When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.

Some Interview Question:

1.What is polymorphism and what are the types of it?
Polymorphism in java is a concept by which we can perform a single action by different ways
Method overloading(compile time polymorphism),method overriding(run time polymorphism)

2.What is method overriding?
Specific implementation of a method for child class.

3.What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method Overloading

4.What is static and dynamic binding?
static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at run time.

5.can we overload main() method?
Yes,  we can have many main() methods in a class by overloading the main method.

Java- Overloading Method


Overloading Method : 

              If a class have multiple methods by same name but different parameters, it is known as Method Overloading. Method overloading increases the readability of the program. It is also known as Static Polymorphism or compile time Polymorphism. 

Points to considered for overloading when method name is same:

  1. The number of parameters is different for the methods.
  2. The parameter types are different (like changing a parameter that was a float to an int). 
  3. Sequence of Data type of parameters. 
  4. Constructor in Java can be overloaded
  5. Overloading can take place in the same class or in its sub-class.

Points when overloading not considered :

  1. Just changing the return type of the method.  If the return type of the method is the only thing changed, then this will result in a compiler error.  
  2. Changing just the name of the method parameters, but not changing the parameter type.If the name of the method parameter is the only thing changed then this will also result in a compiler error

Example of Overloading : 

As explained earlier overloading done at compile time..
Overloading in same class..


















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

Overloading in Sub Class...



Tuesday, 14 April 2015

Selenium - Web table in Selenium Webdriver

Web table is a different type of web element and we can not directly get all data in one variable.
To access web table data we need to locate web table using findelement method and then identified all the tr tags using findelements method.
Code for the same as below.

WebDriver driver =  new InternetExplorerDriver();
WebElement table = driver.findElement(By.id("tableid));
List<WebElement> tablerows = table.findElements(By.tagName("tr")); // To get all Rows

int rowcount  =  tablerows.size();  \\To get count of total rows

for (WebElement tablerow : tablerows )
{
tablerowindex = 0;
     List <WebElement> tablecolumns = tablerow.findelements(By.tagName("td"));
     int columncount = tablecolumns.size();
     for (WebElement tablecolumn : tablecolumns)
     {




      }



Selenium - Multiple windows in Selenium Webdriver

Selenium can handle multiple windows using inbuilt method getWindowHandles().
Code for the same as below.

WebDriver driver =  new InternetExplorerDriver();
Set<String> allWindows =  driver,getWindowHandles();

for (String allWindow : allWindows ) {
driver.switchTo().window(allWindow);

if (driver.getTitle().equalsIgnoreCase("VIP Database")){
              driver.manage().window().maximize(); 
              driver.findElement(By.cssSelector("button")).click();
          }
}

Selenium - Implicit wait and Explicit wait in Selenium Webdriver

Difference between Implicit wait and Explicit Wait...


Implicit Wait Explicit Wait
Implicit wait used for all the element search Explicit wait is specific to the element and is more flexible compare to Implicit wait. 
Implicit wait is time based. where we can command selenium WebDriver to wait for specific time. e.g 30 sec or 1 min and if till given time element not found than throws NoSuchElementexception. Explicit wait is condition based with time. In this we can command selenium WebDriver to wait for any condition and if condition not satisfied till given time then throws exception  
By default Implicit wait is 0.No default value
We need to provide two parameter to define implicit wait, Time to wait and UnitExplicit wait is programmatic.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions. elementToBeClickable(By.id("txtuser")));

One drawback of implicit wait is it affects performance of the automation execution as it waits for all the element for given time. And we need to give time of the slowest element to load.alertIsPresent ()
elementSelectionStateToBe :
elementToBeClickable
elementToBeSelected
envisibilityOfElementLocated 
and many more...


Monday, 13 April 2015

Selenium - Alert, Confirmation message or error message in Selenium WebDriver

Handling of Alert, Confirmation Message or error message while execution is very important for smooth execution.

Alerts:

public class alertWindow {


public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
WebElement button , textarea = null;
String parentWindowHandle = null;
Wait<WebDriver> wait = null;
Alert alert =null;

driver.get(System.getProperty("user.dir")+ "\\Sample\\Prompt.html");
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 10);
parentWindowHandle = driver.getWindowHandle();
button = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button")));
button.click();

if (alert != null)
System.out.println("Alert Not found");
else
System.out.println("Alert found");

alert = driver.switchTo().alert();
System.out.println("Alert Text " + alert.getText());

alert.sendKeys("Mohit Jain");
alert.accept();

textarea = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("demo")));
System.out.println(textarea.getText());

button.click();
alert.dismiss();
textarea = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("demo")));
System.out.println(textarea.getText());

driver.quit();

}

}

Confirmation :  

public class confirmationMesg {

/**
* @param args
*/
public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
WebElement button ,firstname, textarea = null;
String parentWindowHandle = null;
Set<String> allWindows;
Wait<WebDriver> wait = null;
Alert alert =null;
String windowtitle =null;

driver.navigate().to("http://www.ranorex.com/web-testing-examples/vip/");
driver.manage().window().maximize();
firstname =driver.findElement(By.id("FirstName"));
//firstname.sendKeys("Mohit");
button = driver.findElement(By.id("Save"));
parentWindowHandle = driver.getWindowHandle();
button.click();

allWindows = driver.getWindowHandles();
/*
for (String allWindow : allWindows ) {

driver.switchTo().window(allWindow);
if (driver.getTitle().equalsIgnoreCase("VIP Database")){

driver.manage().window().maximize();
driver.findElement(By.cssSelector("button")).click();

}



}
driver.switchTo().window(parentWindowHandle);
firstname.sendKeys("Mohit");*/

for (String allWindow : allWindows ) {

driver.switchTo().window(allWindow);
driver.manage().window().maximize();
if (driver.getTitle().equalsIgnoreCase("VIP Database")){
//driver.close();
driver.quit();
}

}
}



Tuesday, 24 March 2015

Selenium - findelements method in selenium webdriver

findElements method is used to locate multiple web element with same attribute.like all the element with type button on the page. It returns list of web element. if no element found then a empty list will be return. Like findelement it will not return null or raise any exception if no element found.

Code for play with findelements as below..

WebDriver driver = new InternetExplorerDriver();
List <webElement> elements = driver.findElements(By.className("button"));

for (WebElement element : elements )
   {
      String elmtext = element.getText();  / to get text from web element.
      boolean dis = element.isDisplayed(); //to check if web element is displayed.
    } 




Monday, 23 March 2015

Selenium - Open URL of the application in Selenium ?

First we need to set internet explorer exe path and initiate Webdriver using below code.

public class BrowserStart {
  
    public static WebDriver driver;
  
    public static void loadbrowser () throws InterruptedException{
      
        //Set Internetexplorer exe path..
      
        File file = new File(System.getProperty("user.dir") + "/libs/IEDriverServer.exe");
        System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
      
         driver = new InternetExplorerDriver();
        driver.get("http://www.google.com");

      }
}

Selenium - Web Element on webpage in Selenium

1. Edit Box:


Enter "Hello" word in edit box...

WebDriver driver = new InternetExplorerDriver();
WebElement element = driver.findElement(By.ID("txtbx"));
element.clear();    \\ Clear text box 
element.sendKeys("Hello");

2. Drop Down :

Select "India" from country drop down.

WebDriver driver = new InternetExplorerDriver();
WebElement element = driver.findElement(By.ID("dcountry"));
new Select(element).selectByVisibleText("India");

Also we can select by index.
new Select(element).selectByIndex(1);
or
 new Select(element).selectByValue("India");

we can also deselect value from drop down using below code.
new Select(element).deselectByValue("India");

3. Radio button:

Select one of the type radio button.
WebDriver driver = new InternetExplorerDriver();
WebElement element = driver.findElement(By.ID("type"));
element.click();
element.isSelected; // To check if radio button is clicked.

in case of multiple radio button and if we want to select one of the radio button then we can use findByElements to locate list of the radio button.

List <WebElement> radiolist = driver.findElements(By.ID("type"));

4. Checkbox :

Select one of the option checkbo.
WebDriver driver = new InternetExplorerDriver();
WebElement element = driver.findElement(By.ID("option"));
element.click();
element.isSelected; // To check if check box is clicked.

in case of multiple checkboxes and if we want to select one of the checkbox then we can use findByElements to locate list of the checkbox.

List <WebElement> radiolist = driver.findElements(By.ID("option"));

5. WebButton:

To click on web Button or submit form details .

WebDriver driver = new InternetExplorerDriver();
WebElement element = driver.findElement(By.ID("submit"));
element.click();
or
element.submit();

element.isEnabled();        //  To check in button is enable or dissable..
element.isDisplayed();    // To check if button is visible ot not..

Sunday, 22 March 2015

Selenium - Difference between findelement () and findelements ()..???

findElement :

 findElement method is used to locate single element .findelement method returns first matching element of given locator found on the web page . Return type is WebElement object. If no element found then it throw nosuchelement exception.

WebDriver driver = new internetExplorerDriver();
WebElement element = driver.findElement(by.ID("txtbox"));

findElements:

findelements method used to locate multiple element on web page with given attribute. like all the check boxes with same ID. Return type is list. if no element found then return empty list of webElement object.

List<WebElement> types= driver.findElements(By.xpath("//type")); 
int size = types.size();
 

Selenium - Different types of Web element locator in Selenium WebDriver


Locating elements in WebDriver can be done on the WebDriver instance itself or on a WebElement.we have to use finelement method. it returns WebElement object if element found else returns nosuchelementfound exception.
Different types of locator as below.

1.  By.ID: 

Locating web element by ID is simplest and easy way. Use this when we know id attribute of an element

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.ID("txtboxid"));

If web element ID not defined by UI developer or element ID is not unique or its generated at run time then we can not use By.ID locator.

2. By.Name : 

Like ID we can also use Name attribute of web element to locate the same.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.Name("txtboxname"));

3. By.className:

We can also class attribute to locate web element . In case of multiple element with same class name than it returns first element with classname.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.className("txtclassname"));

4. By.linkText

 We can use link text to locate a link element.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.linkText("txtlink"));

5. By.partialLinkText

Like linkText we can also locate link element by partial link text.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.partialLinkText("txtlinktext"));

6.  By.Xpath:

Web element can be located using xpath. At a high level, WebDriver uses a browser’s native XPath capabilities wherever possible.  Xpath is useful when we don't know ID or Name attribute.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.Xpath("//html/body/form[1]"));

7. By.CSS Selector:

Like Xpath we can also use CSS selector. CSS is cascade style sheet.

   WebDriver driver = new internetExplorerDriver();
   WebElement elm = driver.findElement(By.cssSelector("//html/body/form[1]"));

Saturday, 21 March 2015

Selenium - When to use Selenium server with Selenium WebDriver?

There are some scenario where we have to use the Selenium-Server with Selenium-WebDriver.
  1. If we are using Selenium-Grid to distribute your tests over multiple machines or virtual machines (VMs).
  2. If we want to connect to a remote machine that has a particular browser version that is not on our current machine.
  3. If we are not using the Java bindings (i.e. Python, C#, or Ruby) and would like to use HTMLunit driver

Selenium - Read Excel sheet using APACHE POI

We can read excel using APACHE POI. its Java API to work with excel sheet.


HSS stands for Horrible spread sheet.

public FileInputStream instr;
public HSSFWorkbook wb = null;
public HSSFSheet ws = null;


            File file = new File(System.getProperty("user.dir"));
            DataFormatter dt = new DataFormatter();

            instr = new FileInputStream(file.getAbsolutePath() + "/Common/Config.xls");
            wb = new HSSFWorkbook(instr);
            ws = wb.getSheet("config");
        
           int row_count = ws.getLastRowNum() +1;           //to get count of total rows...
           int cell_count = ws.getLastCellNum() +1;  

           HSSFRow row = ws.getRow(0);                    //To get 1st row
           String column1text = dt.formatCellValue(row.getCell(0); //read text from first row and column




   

Friday, 20 March 2015

Selenium - Difference between Selenium 1.0 and Selenium 2.0

Selenium 1.0 also known as Selenium RC and Selenium 2.0 known as Seleniuim WebDriver.
Differences as below...

Selenium 1.0 (RC) Selenium 2.0 (WebDriver)
Need to start Remote server before execution.No need to start any server.
Support some of the browser like.. IE, FireFox, Chrome and Opera. Can not support headless HTMLunit driverSupport all the browser like.. IE, FireFox, Chrome ,Opera, headless HTMLunit, Android
Core engine is Javascript basedInteracts natively with browser application
Very complex architectureSimple and easy architecture
It calls Selenium Core to execute and control browserDirectly interact with browser
API are more matured but contain redundancy and often confusingAPI's are simple and no redundancey.
Built in test result generator and automatically generate HTML fileNo Built in result file generator
It ‘injected’ javascript functions into the browser when the browser was loaded and then used its javascript to drive the AUT within the browserSelenium-WebDriver makes direct calls to the browser using each browser’s native support for automation

Thursday, 19 March 2015

Selenium - Selenium 2.0


Selenium 2.0 is latest version of selenium open source tool. Selenium 2.0 also known as Selenium WebDriver. Selenium is automation testing tool for Web based application. WebDriver is a name of API. We cannot automate desktop application using Selenium open source tool. older version of Selenium is Selenium 1.0 also known as Selenium RC.