Automation Using Selenium Webdriver

Thursday, 3 November 2016

Java Difference Between

Difference Between

Difference between non-static and static variable ?

Non-Static methodStatic method
1These method never be preceded by static keyword
Example:
void fun1()
{
 ......
 ......
}
These method always preceded by static keyword
Example:
static void  fun2()
{
......
......
}
2Memory is allocated multiple time whenever method is calling.Memory is allocated only once at the time of loading.
3It is specific to an object so that these are also known as instance method.These are common to every object so that it is also known as member method or class method.
4These methods always access with object reference
Syntax:
Objref.methodname();
These property always access with class reference
Syntax:
className.methodname();
5If any method wants to be execute multiple time that can be declare as non static.If any method wants to be execute only once in the program that can be declare as static .

Difference between Method and Constructor

MethodConstructor
1Method can be any user defined nameConstructor must be class name
2Method should have return typeIt should not have any return type (even void)
3Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
1Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Difference between package keyword and import keyword

  • Package keyword is always used for creating the undefined package and placing common classes and interfaces.
  • import is a keyword which is used for referring or using the classes and interfaces of a specific package.

Difference between Class and Object

ClassObject
1Class is a container which collection of variables and methods.object is a instance of class
2No memory is allocated at the time of declarationSufficient memory space will be allocated for all the variables of class at the time of declaration.
3One class definition should exist only once in the program.For one class multiple objects can be created.

Difference between Statement and PreparedStatement ?

StatementPreparedStatement
1Statement interface is slow because it compile the program for each executionPreparedStatement interface is faster, because its compile the command for once.
2We can not use ? symbol in sql command so setting dynamic value into the command is complexWe can use ? symbol in sql command, so setting dynamic value is simple.
3We can not use statement for writing or reading binary data (picture)We can use PreparedStatement for reading or writing binary data.

Difference between throw and throws ?

throwthrows
1throw is a keyword used for hitting and generating the exception which are occurring as a part of method bodythrows is a keyword which gives an indication to the specific method to place the common exception methods as a part of try and catch block for generating user friendly error messages
2The place of using throw keyword is always as a part of method body.The place of using throws is a keyword is always as a part of method heading
3When we use throw keyword as a part of method body, it is mandatory to the java programmer to write throws keyword as a part of method headingWhen we write throws keyword as a part of method heading, it is optional to the java programmer to write throw keyword as a part of method body.

Difference between checked Exception and un-checked Exception ?

Checked ExceptionUn-Checked Exception
1checked Exception are checked at compile timeun-checked Exception are checked at run time
2e.g.
IOException, SQLException, FileNotFoundException etc.
e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberNotFoundException etc.

Difference between Abstraction and Encapsulation ?

Encapsulation is not provides fully security because we can access private member of the class using reflation API, but in case of Abstraction we can't access static, abstract data member of class.

Difference between Abstract and Interface ?

AbstractInterface
1It is collection of abstract method and concrete methods.It is collection of abstract method.
2There properties can be reused commonly in a specific application.There properties commonly usable in any application of java environment.
3It does not support multiple inheritance.It support multiple inheritance.
4Abstract class is preceded by abstract keyword.It is preceded by Interface keyword.
5Which may contain either variable or constants.Which should contains only constants.
6The default access specifier of abstract class methods are default.There default access specifier of interface method are public.
7These class properties can be reused in other class using extend keyword.These properties can be reused in any other class using implements keyword.
8Inside abstract class we can take constructor.Inside interface we can not take any constructor.
9For the abstract class there is no restriction like initialization of variable at the time of variable declaration.For the interface it should be compulsory to initialization of variable at the time of variable declaration.
10There are no any restriction for abstract class variable.For the interface variable can not declare variable as private, protected, transient, volatile.
11There are no any restriction for abstract class method modifier that means we can use any modifiers.For the interface method can not declare method as strictfp, protected, static, native, private, final, synchronized.

Difference between Overloading and Overriding ?

OverloadingOverriding
1Whenever same method or Constructor is existing multiple times within a class either with different number of parameter or with different type of parameter or with different order of parameter is known as Overloading.Whenever same method name is existing multiple time in both base and derived class with same number of parameter or same type of parameter or same order of parameters is known as Overriding.
2Arguments of method must be different at least arguments.Argument of method must be same including order.
3Method signature must be different.Method signature must be same.
4Private, static and final methods can be overloaded.Private, static and final methods can not be overrided.
5Access modifiers point of view no restriction.Access modifiers point of view not reduced scope of Access modifiers but increased.
6Also known as compile time polymorphism or static polymorphism or early binding.Also known as run time polymorphism or dynamic polymorphism or late binding.
7Overloading can be exhibited both are method and constructor level.Overriding can be exhibited only at method leve.
8The scope of overloading is within the class.The scope of Overriding is base class and derived class.
9Overloading can be done at both static and non-static methods.Overriding can be done only at non-static method.
10For overloading methods return type may or may not be same.For overriding method return type should be same.

Difference between sleep() and suspend() ?

Sleep() can be used to convert running state to waiting state and automatically thread convert from waiting state to running state once the given time period is completed. Where as suspend() can be used to convert running state thread to waiting state but it will never return back to running state automatically.

Difference between String and StringBuffer ?

StringStringBuffer
1The data which enclosed within double quote (" ") is by default treated as String class.The data which enclosed within double quote (" ") is not by default treated as StringBuffer class
2String class object is immutableStringBuffer class object is mutable
3When we create an object of String class by default no additional character memory space is created.When we create an object of StringBuffer class by default we get 16 additional character memory space.

Difference between StringBuffer and StringBuilder ?

All the things between StringBuffer and StringBuilder are same only difference is StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time so it not thread safe.
StringBufferStringBuilder
1It is thread safe.It is not thread safe.
2Its methods are synchronized and provide thread safety.Its methods are not synchronized and unable to provide thread safety.
3Relatively performance is low because thread need to wait until previous process is complete.Relatively performance is high because no need to wait any thread it allows multiple thread at a time.
1Introduced in 1.0 version.Introduced in 1.5 version.

Difference between Method and Constructor ?

MethodConstructor
1Method can be any user defined nameConstructor must be class name
2Method should have return typeIt should not have any return type (even void)
3Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
1Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Difference between non-static and static Method

Non-Static methodStatic method
1These method never be preceded by static keyword
Example:
void fun1()
{
 ......
 ......
}
These method always preceded by static keyword
Example:
static void  fun2()
{
......
......
}
2Memory is allocated multiple time whenever method is calling.Memory is allocated only once at the time of class loading.
3It is specific to an object so that these are also known as instance method.These are common to every object so that it is also known as member method or class method.
4These methods always access with object reference
Syntax:
Objref.methodname();
These property always access with class reference
Syntax:
className.methodname();
5If any method wants to be execute multiple time that can be declare as non static.If any method wants to be execute only once in the program that can be declare as static .

Difference between non-static and static variable

Non-static variableStatic variable
1These variable should not be preceded by any static keyword Example:
class  A
{
int a;
}
These variables are preceded by static keyword.

Example

class  A
{
static int b;
}
2Memory is allocated for these variable whenever an object is createdMemory is allocated for these variable at the time of loading of the class.
3Memory is allocated multiple time whenever a new object is created.Memory is allocated for these variable only once in the program.
4Non-static variable also known as instance variable while because memory is allocated whenever instance is created.Memory is allocated at the time of loading of class so that these are also known as class variable.
5Non-static variable are specific to an objectStatic variable are common for every object that means there memory location can be sharable by every object reference or same class.
6Non-static variable can access with object reference.

Syntax

obj_ref.variable_name
Static variable can access with class reference.

Syntax

class_name.variable_name

Wednesday, 2 November 2016

Checking text on web page using WebDriver

While testing any web application, we need to make sure that it is displaying correct text under given elements. Selenium WebDriver provides a method to achieve this. We can retrieve the text from any WebElement using getText() method.

Example
Lets create a test that check for the proper text in flipkart menu tab.

Code:
@Test
public void testFlipkartMenuText() {
    //Get Text from first item and store it in String variable
    String electronics = driver.findElement(By.cssSelector("li[data-key='electronics']>a>span")).getText();
 
    //Compare actual & required texts
    assertEquals("Electronics",electronics); 
}
The WebElement class' getText() method returns value of the innerText attribute
of the element.

P.S : Given script may not work on flipkart site. I've written this code just to give some basic idea of using getText() method

Generate Random Date in between Start Date and End Date(Java)

Generate Random Date in between Start Date and End Date(Java)

Generating random Date using java for Selenium WebDriver by taking inputs as format of date,Start date and End Date.
Please find the below Reusable method for the same

Sample Code for generating Random Date in between Start Date and End Date(Java)::

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GenerateRandomDate {



public static String generateRandomDate(String Format,String startDate,String endDate) throws ParseException
  {
   DateFormat formatter = new SimpleDateFormat(Format);
   Calendar cal=Calendar.getInstance();
   cal.setTime(formatter.parse(startDate));
   Long value1 = cal.getTimeInMillis();

   cal.setTime(formatter.parse(endDate));
   Long value2 = cal.getTimeInMillis();

   long value3 = (long)(value1 + Math.random()*(value2 - value1));
   cal.setTimeInMillis(value3);
   return formatter.format(cal.getTime());
     }



    public static void main(String args[]) throws ParseException{
   
     System.out.println(GenerateRandomDate.generateRandomDate("dd MMM yyyy", "01 Aug 2016", "01 Sep 2017"));
   
   
    }

}

Advanced TestNG Interview Questions

 #1) What is the significance of <testng.xml> file?

Answer: In a Selenium TestNG project, we use testng.xml file to configure the complete test suite into
a single file. This file makes it easy to group all the test suites and their parameters in one file.
It also gives the ability to pull out subsets of your tests or split several runtime configurations.
Few of the tasks which we can group in the <testng.xml> file are as follows.

1- Can configure test suite comprising of multiple test cases to run from a single place.
2- Can include or exclude test methods test execution.
3- Can mark a group to include or exclude.
4- Can pass parameters in test cases.
5- Can add group dependencies.
6- Can configure parallel test execution.
7- Can add listeners.



Question #2) How to pass parameter through <testng.xml> file to a test case?

Answer: You can set the parameter using the below syntax in the <testng.xml> file.


<parameter name="browser" value="FFX" />
1
<parameter name="browser" value="FFX" />
Here, name attribute represents the parameter name and value signifies the value of that parameter. Then we can use that parameter in the selenium WebDriver software automation test case using the bellow syntax.

Java

@Parameters ({"browser"})
1
@Parameters ({"browser"})


Question #3) How to exclude a @Test method from a test case with two @Test methods? Is it possible?

Answer: Yes, you need to add @Test method in the exclude tag of <testng.xml> file as mentioned below.


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Exclusion Suite">
<test name="Exclusion Test" >
<classes>
<class name="Your Test Class Name">
<methods>
<exclude name="Your Test Method Name To Exclude"/>
</methods>
</class>    
</classes>
</test>
</suite>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test Exclusion Suite">
  <test name="Exclusion Test" >
    <classes>
      <class name="Your Test Class Name">
       <methods>
       <exclude name="Your Test Method Name To Exclude"/>
      </methods>
      </class>    
    </classes>
  </test>
</suite>


Question #4) How to skip a @Test method from execution?

Answer: You can use the below syntax inside @Test method to skip a test case from test execution.

Java

throw new SkipException("Test Check_Checkbox Is Skipped");
1
throw new SkipException("Test Check_Checkbox Is Skipped");
It will throw skip exception and @Test method will be ignored immediately from execution.



Question #5) Can you arrange the below <testng.xml> tags from parent to child?

<test>
<suite>
<class>
<methods>
<classes>

Answer: The <testng.xml> file will have the following structure.

The parent tag in the <testng.xml> file is the <suite> tag.
<suite> tag can include one or more <test> tags.
<test> tag can include the <classes> tag.
<classes> tag can include one or more <class> tags.
<class> tag wraps the <methods> tag where we define the test methods to include or exclude.
Hence, the correct order of the TestNG tags would be.

<suite>
<test>
<classes>
<class>
<methods>



Question #6) How to define the priority of @Test method? Also, mention its usage?

Answer:

In your Selenium WebDriver project, you can set priority for TestNG @Test annotated methods as shown
in the following example.

Java

@Test(priority=0)
1
@Test(priority=0)
Using priority, you can manage @Test method execution sequence as per your requirement.
That means @Test method with priority = 0 will run 1st and @Test method with priority = 1 will execute
2nd and so on.



Question #7) Can you specify any 6 assertions of TestNG to be used in a Selenium WebDriver software
testing tool.

Answer: There are multiple assertions available In TestNG but generally we use the following assertions

 in out test cases.

1- assertEquals
2- assertNotEquals
3- assertTrue
4- assertFalse
5- assertNull
6- assertNotNull



Question #8) Why soft assertion is used in Selenium WebDriver and TestNG automation project?

Answer: TestNG soft assertion allows to continue the test execution even if the assertion is failed.
That means once the soft assertion fails, remaining part of <@Test> method is executed and the assertion
failure is reported at the end of <@Test> method.



Question #9) How to apply regular expression in <testng.xml> file to find @Test methods containing “product” keyword?

Answer:

Refer below example, here we’ve used a regular expression to find @Test methods containing keyword “product”.


<methods>
<include name=".*product.*"/>
</methods>
1
2
3
<methods>
     <include name=".*product.*"/>
</methods>


Question #10) What are the time unit we specify in test cases and test suites? minutes? seconds? milliseconds? or hours? Give Example.

Answer: Time unit we specify at @Test method level and test suite level which normally set in milliseconds unit.



Question #11) List out the benefits of TestNG over Junit?

Answer:
TestNG framework has following benefits over JUnit.

1- TestNG annotations are more logical and easier to understand.

2- Unlike JUnit, TestNG does not require to declare @BeforeClass and @AfterClass.

3- There is no method name constraint in Selenium TestNG framework.

4- TestNG supports three additional setups:

4.1- @Before/AfterSuite,

4.2- @Before/AfterTest, and

4.3- @Before/AfterGroup.

5- In Selenium TestNG projects, there is no need to extend any class.

7- In TestNG, it is possible to run Selenium test cases in parallel.

8- TestNG supports grouping of test cases which is not possible in JUnit.

9- Based on the group, TestNG allows you to execute the test cases.

10- TestNG permits you to determine the dependent test cases. Every test case is autonomous to other
 test cases.



Question #12) What are the basic steps for drafting TestNG test cases?

Answer:

Following are the most common steps for writing TestNG test cases.

1- Write down the business logic of your test.

2- Add appropriate TestNG annotations in your code.

3- In <build.xml> or <testing.xml>, add the information about your test.

4- Run your TestNG project.



Question #13) List out different ways to run TestNG?

Answer:

You can run TestNG in the following ways.

1- Start directly from the Eclipse IDE, or

2- Run using the IntelliJ’s IDEA IDE.

3- Run with ant build tool.

4- Launch from the command line.



Question #14) In TestNG how can you disable a test?

Answer:

To disable the test case, you can use the following annotation.

@Test(enabled = false).


Question #15) Explain what does the test timeout mean in TestNG?

Answer: The timeout test in TestNG is nothing but the time allotted to perform unit testing.
If the unit test fails to finish in that specific time limit, TestNG will abandon further testing and
mark it as a failed.



Question #16) What is exception test and why is it used for?

Answer:

TestNG provides an option for tracing the Exception handling of code. You can verify whether a code
throws the desired exception or not. The expectedExceptions parameter is availed along with @Test
annotation. Please refer the below example for clarity.

Java

package com.techbeamers.testng.examples.exception;
import org.testng.annotations.Test;
public class TestRuntime {
@Test(expectedExceptions = { IOException.class })
public void exceptionTestOne() throws Exception {
throw new IOException();
}
@Test(expectedExceptions = { IOException.class, NullPointerException.class })
public void exceptionTestTwo() throws Exception {
throw new Exception();
}}


package com.techbeamers.testng.examples.exception;

import org.testng.annotations.Test;

public class TestRuntime {

@Test(expectedExceptions = { IOException.class })

 public void exceptionTestOne() throws Exception {

 throw new IOException();

 }

 @Test(expectedExceptions = { IOException.class, NullPointerException.class })

 public void exceptionTestTwo() throws Exception {

 throw new Exception();

 }

}


Question #17) Explain what is parametric testing?

Answer:

Parameterized testing lets the programmer re-run the same test with different values. TestNG allows
you to pass parameters directly to the test methods using the two ways as given below.

1- With testing.xml.

2- With Data Providers.



Question #18) Explain what does @Test(invocationCount=?) and (threadPoolSize=?) indicates?

Answer:

1- @Test (threadPoolSize=?): The threadPoolSize attribute directs TestNG to create a thread pool to run
 the test method through multiple threads. With thread pool, the running time of the test method
reduces considerably.

2- @Test(invocationCount=?): The invocation count refers to the no. of times TestNG should run the test method.



Question #19) What are the different ways to produce reports for TestNG results?

Answer:

TestNG offers following two ways to produce a report.

Listeners: For a listener class, the class has to implement the org.testng./TestListener interface. TestNG notifies these classes at runtime when the test enters into any of the below states.
e.g. Test begins, finishes, skips, passes or fasils.

Reporters: For a reporting class to implement, the class has to implement an org.testng/Reporter interface. When the whole suite run ends, these classes are called. When called, the object consisting the information of the whole test run is delivered to this class.



Question #20) How does TestNG allow you to state dependencies?

Answer:
TestNG supports two ways to declare the dependencies.

1- Using attributes dependsOnMethods in @Test annotations.

2- Using attributes dependsOnGroups in @Test annotations.

verify element existence using Selenium Webdriver

In this article, one of the way to validate existence of multiple objects of same object type based
on element text in the application is explained using Selenium Webdriver with java.
Please share other better way to verify element existence using Selenium Webdriver.

public boolean IsElementExists(String ObjectType, String strElemText)
{
 boolean boolElemExists = false;
//In case of multiple objects which needs to be validated, Provide multiple objects
// text seperated by  | in strElemText. e.g: strElemText as "mail|inbox"
// Create an array by splitting array based on delimiter "|"
 String[] elemTextArray = strElemText.split("|");
// Loop through array elements
 for ( int j = 0;j<elemTextArray.length;j++)
 {
  List<WebElement> lstElement = null;
  try
// Better approach will be to pass values from enum for Object type
   switch (ObjectType)
   {
   // in case of link object storing all the elements of type link in lstElement
   case "Link":
     lstElement = driver.findElements(By.tagName("a"));
    break;
    // in case of link object storing all the elements of type link in label
   case "Label":
    lstElement = driver.findElements(By.tagName("label"));
    break;
   }
   for (int i=0;i<lstElement.size();i++)
   {
    if (lstElement.get(i).getText().contentEquals(strElemText.trim()))
      {
       boolElemExists = true;
       i= lstElement.size()-1;
      }
   }
   if (boolElemExists = false)
   {
    return false;
   }
   }
  catch(Exception e)
  {
   return false;
  }
 }
 return boolElemExists;
}

Tuesday, 1 November 2016

MySQL database connectivity Selenium Script


Selenium Script for MySQL database connectivity

Prerequisite:

Download - mysql-connector-java-latest-bin.jar and add it to your project

import java.sql.*;
import javax.sql.*;

public class dbconnection{

public static void main(String args[]){
   String username;
   String dbUrl = "jdbc:mysql://localhost:3306/test";  //This URL is based on your IP address
   String username="username"; //Default username is root
   String password="password"; //Default password is root
   String dbClass = "com.mysql.jdbc.Driver";
   String query = "Select username from users where user_id = 1;";
  try {
      Class.forName(dbClass);
      Connection con = DriverManager.getConnection (dbUrl,username,password);
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()){
        dbtime = rs.getString(1);
        System.out.println(username);
       } //end while

  con.close();
  } //end try

catch(ClassNotFoundException e) {
e.printStackTrace();
}

catch(SQLException e) {
e.printStackTrace();
}

}  //end main

}  //end class

Read-Write Text File In Java - Tutorials For WebDriver

We have learnt about String class and Its different functions In my previous post.
Now our next topic Is How to write In to text file or How to read text file In java software
development language. Many times you will need reading or writing text file In your selenium webdriver
software automation test case development. For Example, You are reading some large data from
web page of software web application and wants to store It In text file to use It somewhere else In
future. Same way, You have to read data from file for some purpose.

It Is very easy to Create, Write and read text file In java software development language.
We can use java built in class File to create new file, FileWriter and BufferedWriter class to write
In to file, FileReader and BufferedReader class to read text file.

Bellow given example will first of all create temp.txt file In D: drive and then write two line In to
It. Then It will read both lines one by one from text file using while loop and print In console.
You can use bellow given example code of software development language for reading or writing text
 file In your selenium webdriver software automation test case whenever needed.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class RW_File {

 public static void main(String[] args) throws IOException {
  //Create File In D: Driver.
  String TestFile = "D:\\temp.txt";
  File FC = new File(TestFile);//Created object of java File class.
  FC.createNewFile();//Create file.

  //Writing In to file.
  //Create Object of java FileWriter and BufferedWriter class.
  FileWriter FW = new FileWriter(TestFile);
  BufferedWriter BW = new BufferedWriter(FW);
  BW.write("This Is First Line."); //Writing In To File.
  BW.newLine();//To write next string on new line.
  BW.write("This Is Second Line."); //Writing In To File.
  BW.close();

  //Reading from file.
  //Create Object of java FileReader and BufferedReader class.
  FileReader FR = new FileReader(TestFile);
  BufferedReader BR = new BufferedReader(FR);
  String Content = "";

  //Loop to read all lines one by one from file and print It.
  while((Content = BR.readLine())!= null){
   System.out.println(Content);
  }
 }
}