AUTOMATION TUTORIAL QTP, UFT & Selenium Online Tutorial Fri, 01 Dec 2017 11:28:33 +0000 en-US hourly 1 https://wordpress.org/?v=4.5.3 OOPS interview Questions and Answers Part – 2 /interview-questions/oops-interview-questions-and-answers-part-2/ /interview-questions/oops-interview-questions-and-answers-part-2/#respond Tue, 22 Aug 2017 06:18:39 +0000 /?p=720 What is function overloading?

Function overloading is defined as a normal function, but it has the ability to perform different tasks. It allows creation of several methods with the same name which differ from each other by type of input and output of the function.

Example

void add(int &a, int &b);

void add(double &a, double &b);

What is Inline function?

Inline function is a technique used by the compilers and instructs to insert complete body of the function wherever that function is used in the program source code.

What is a virtual function?

Virtual function is a member function of class and its functionality can be overridden in its derived class. This function can be implemented by using a keyword called virtual, and it can be given during function declaration.

Virtual function can be achieved in C++, and it can be achieved in C Language by using function pointers or pointers to function.

What is friend function?

Friend function is a friend of a class that is allowed to access to Public, private or protected data in that same class. If the function is defined outside the class cannot access such information.

Friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public or protected.

What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the arguments. Operator,-,* can be used to pass through the function , and it has their own precedence to execute.

Example:

class complex {

double real,

imag; public: complex(double r, double i) : real(r),

imag(i) {} complex operator+(complex a, complex b);

complex operator*(complex a, complex b);

complex& operator=(complex a, complex b);

}

What is an abstract class?

An abstract class is a class which cannot be instantiated. Creation of an object is not possible with abstract class, but it can be inherited. An abstract class can contain only Abstract method. Java allows only abstract method in abstract class while for other language it allows non-abstract method as well.

What is a ternary operator?

Ternary operator is said to be an operator which takes three arguments. Arguments and results are of different data types, and it is depends on the function. Ternary operator is also called as conditional operator.

What is the use of finalize method?

Finalize method helps to perform cleanup operations on the resources which are not currently used. Finalize method is protected, and it is accessible only through this class or by a derived class.

What are different types of arguments?

A parameter is a variable used during the declaration of the function or subroutine and arguments are passed to the function, and it should match with the parameter defined. There are two types of Arguments.

  • Call by Value – Value passed will get modified only inside the function, and it returns the same value whatever it is passed it into the function.
  • Call by Reference – Value passed will get modified in both inside and outside the functions and it returns the same or different value.

What is super keyword?

Super keyword is used to invoke overridden method which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.

It also forwards a call from a constructor to a constructor in the superclass.

What is method overriding?

Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will overrides the implementation in the superclass by providing the same method name, same parameter and same return type.

What is an interface?

An interface is a collection of abstract method. If the class implements an inheritance, and then thereby inherits all the abstract methods of an interface.

What is exception handling?

Exception is an event that occurs during the execution of a program. Exceptions can be of any type – Run time exception, Error exceptions. Those exceptions are handled properly through exception handling mechanism like try, catch and throw keywords.

Difference between overloading and overriding?

Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same method with different arguments, and it may or may not return the same value in the same class itself.

Overriding is the same method names with same arguments and return types associates with the class and its child class.

Difference between class and an object?

An object is an instance of a class. Objects hold any information, but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object.

Class can have sub-classes, and an object doesn’t have sub-objects.

What is an abstraction?

Abstraction is a good feature of OOPS, and it shows only the necessary details to the client of an object. Means, it shows only necessary details for an object, not the inner details of an object. Example – When you want to switch on television, it not necessary to show all the functions of TV. Whatever is required to switch on TV will be showed by using abstract class.

What are access modifiers?

Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 5 types of access modifiers, and they are as follows:.

  •  Private.
  • Protected.
  • Public.
  • Friend.
  • Protected Friend.

What is sealed modifiers?

Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers can also be applied to properties, events and methods. This modifier cannot be applied to static members.

 How can we call the base method without creating an instance?

Yes, it is possible to call the base method without creating an instance. And that method should be,.

Static method.

Doing inheritance from that class.-Use Base Keyword from derived class.

What is the difference between new and override?

The new modifier instructs the compiler to use the new implementation instead of the base class function. Whereas, Override modifier helps to override the base class function.

What are the various types of constructors?

There are three various types of constructors, and they are as follows:.

– Default Constructor – With no parameters.

– Parametric Constructor – With Parameters. Create a new instance of a class and also passing arguments simultaneously.

– Copy Constructor – Which creates a new object as a copy of an existing object.

What is early and late binding?

Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.

What is ‘this’ pointer?

THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates between the current object with the global object. Basically, it refers to the current object.

What is the difference between structure and a class?

Structure default access type is public, but class access type is private. A structure is used for grouping data whereas class can be used for grouping data and methods. Structures are exclusively used for data and it doesn’t require strict validation, but classes are used to encapsulates and inherit data which requires strict validation.

What is the default access modifier in a class?

The default access modifier of a class is Private by default.

What are all the operators that cannot be overloaded?

Following are the operators that cannot be overloaded -.

  1. Scope Resolution (:: )
  2. Member Selection (.)
  3. Member selection through a pointer to function (.*)

 What is dynamic or run time polymorphism?

Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden function is resolved during run time, not at the compile time. It means having two or more methods with the same name, same signature but with different implementation.

Do we require parameter for constructors?

No, we do not require parameter for constructors.

 What is a copy constructor?

This is a special constructor for creating a new object as a copy of an existing object. There will be always only on copy constructor that can be either defined by the user or the system.

]]>
/interview-questions/oops-interview-questions-and-answers-part-2/feed/ 0
Software Automation Estimation Process – Test Estimation Techniques used in SDLC /interview-questions/software-automation-estimation-process-test-estimation-techniques-used-in-sdlc/ /interview-questions/software-automation-estimation-process-test-estimation-techniques-used-in-sdlc/#respond Thu, 06 Apr 2017 09:45:40 +0000 /?p=717 Estimation is the process of finding an estimate or approximation, which is a value that is usable for some purpose even if input data may be incomplete, uncertain, or unstable.

The Estimate is prediction or a rough idea to determine how much effort would take to complete a defined task. Here the effort is the time or cost. A rough idea how long a task would take to complete. An estimate is especially an approximate computation of the probable cost of a piece of work. An estimate is a forecast or prediction and approximate of what it would Cost.

The calculation of test estimation is based on:

  • Past Data and Past experience
  • Available documents and Knowledge
  • Assumptions
  • Calculated risks

The common question is that “Why do we estimate?”
The answer to this question is very simple, it is to avoid the exceeding time and overshooting budgets for testing activities we estimate the task.

Software Estimation Techniques

There are some Software Testing Estimation Techniques which can be used for estimating –

  1. Delphi Technique
  2.  Work Breakdown Structure (WBS)
  3. Functional Point Method
  4. Three Point Estimation

 

]]>
/interview-questions/software-automation-estimation-process-test-estimation-techniques-used-in-sdlc/feed/ 0
OOPS interview Questions and Answers Part -1 /interview-questions/oops-interview-questions-and-answers-part-1/ /interview-questions/oops-interview-questions-and-answers-part-1/#respond Mon, 03 Apr 2017 09:42:54 +0000 /?p=709 What is OOPS?

OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

Write basic concepts of OOPS?

Following are the concepts of OOPS and are as follows:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism.

What is a class?

A class is simply a representation of a type of object. It is the plan/blueprint/template that describe the details of an object.

What is an object?

Object is termed as an instance of a class, and it has its own state, behavior and identity.

What is Encapsulation?

Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can be restricted to the members of that class.

Levels are Public, Protected, Private, Internal and Protected Internal.

What is Polymorphism?

Polymorphism is nothing but assigning behavior or value in a subclass to something that was already declared in the main class. Simply, polymorphism takes more than one form.

What is Inheritance?

Inheritance is a concept where one class shares the structure and behavior defined in another class. If inheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it is called multiple Inheritance.

Define a constructor?

Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object creation. Rules for constructor are –

  • Constructor Name should be same as class name.
  • Constructor must have no return type.

Define Destructor?

Destructor is a method which is automatically called when the object is made of scope or destroyed. Destructor name is also same as class name but with the tilde symbol before the name

]]>
/interview-questions/oops-interview-questions-and-answers-part-1/feed/ 0
Selenium WebDriver – Insert Verification Point /selenium/selenium-webdriver-insert-verification-point/ /selenium/selenium-webdriver-insert-verification-point/#respond Fri, 28 Oct 2016 06:53:16 +0000 /?p=679 A verification point is a specialized step that compares two values and reports the result. A verification point compares the actuals from the test run, with the expected results in the test case.

You use a checkpoint to:

  • Verify the state of an object
  • Confirm that an application performs as expected

A verification point checks whether an application responds appropriately when a user performs tasks correctly while testing application. A verification point ensures that a user is barred from performing certain tasks and confirms that invalid or incomplete data are flagged with appropriate messages.

Inserting a Verification Point

A verification point can be inserted in the WebDriver script. In this section we will lay out a test scenario in which we have expected result and we will try to automate that test scenario.

Test Scenario

Let us take a simple test case for automation from Google Search Application.

Test Objective: To verify that Selenium link is displayed while automationtutorial.com page open through Google search application.

Test Steps:

  1. Open to Google search application
  2. Enter the automationtutorial.com in text box and click Google search
  3. Click on automationtutorial.com link
  4. Verify that Selenium link is displayed in header section.

Expected Result :-   Selenium link should be displayed in header section.

How to Insert a verification Point

Step 1: Right click on your existing MyFrirstWebDriverTest.Java script, Select Copy.

Step 2: Select the tests package folder, right click and select paste

Step 3: In the Name Conflict dialog box, enter name of the script as VerificationPointTest and click OK

Step 4: Double click on the newly created “VerificationPointTest.java” script so that you can see the script.

Now we will insert a verification point.

Step 1: In the script go to the step after which user click the Automationtutorail.com link in Google search application.

Step 2: Now let us find out the XPath or id value for the Selenium link field in the automatiotutorial.com page. To do this, open your Firefox browser, open application URL, search automatiotutorial.com and then click on automatiotutorial.com page.

Step 3: In Firefox browser open Firebug add-on with Firepath view, Click on highlight option and select Location field.

We notice in the above snapshot that Xpath for link field is

Xpath=.//*[@id=’menu-item-4′]/a

and

Id = menu-item-4

Now we know the Xpath or id of the object to locate the object.

We would also need to find out the property value for this object which stores the value “Selenium”. We will again use Firebug to find this out.

Step 4: Click on DOM tab in  Firebug.

Step 5: To get the property name:

  • Click on the highlight icon
  • Then click on the link Selenium
  • Scroll down in the DOM tab to find out which property stores the value “Selenium”

 

In the above snapshot you will notice property name value is storing “Selenium”

Step 6: Now to insert a verification point in the script, we will insert the statement below:

String linkText = driver.findElement(By.xpath(“.//*[@id=’menu-item-4′]/a”)).getAttribute(“innerText”);

in the above statement –

driver.findElement – help to find the element based on locator

By.xpath(“(“.//*[@id=’menu-item-4′]/a”) – helps to locate element based on xpath.

getAttribute – helps us to get the desired property value of the Web Element.

innerText – is the property name which stores the actual value for location

Step 7: Now we would need to compare it with our expected value and report pass or fail. Insert the following statement after the getAttribute statement.

If Else statement is used as a conditional structure.

equalsIgnoreCase method is used for string comparison in java after ignoring the case of string.

System.out.println is used to print output to the cocsole.

Step 8: That’s it. Now we can perform Project > Clean and run the script by selecting the script, right click and select Run as Junit test. Verify the result in the Eclipse console.

Understand how to implement a Few Common Validation

The common type of validation are:

  • Is the page title as expected?
  • Does text exist on the Page/Webelement and is as expected?

Let us look at how to achieve each of these using the WebDriver API.

Page Title Validation

You can get the current page title simple by calling getTitle() on the WebDriver instance. Here is a simple test that would verify the title –

String pageTitle = driver.getTitle();

if (pageTitle.equalsIgnoreCase(AUTOMATION TUTORIAL”)) {

System.out.println(“Page title is correct. Actual page title is  ” + pageTitle);

} else {

System.out.println(“Page title is incorrect. Actual page title is  ” + pageTitle);

}

Page Element Validation

You can use the following approach for validating text within an element. Here we find the element using one of the locator strategies and then call getText() or getAttribute() on the element object returned.

For instance we want to check footer text of automationtutorial.com

We can use gettext method on the footer text field “© Copyright 2016. All Rights Reserved by”

using Firepath verify Xpath for the footer message  –

Xpath = html/body/footer/div[2]/div/div/div[1]/p

String sFootertext = driver.findElement(By.xpath(“html/body/footer/div[2]/div/div/div[1]/p”)).getText();

if (sFootertext.equalsIgnoreCase(“© Copyright 2016. All Rights Reserved by”)) {

sFootertext .out.println(“Footer text is correct. Actual Footer text is  ” + sFootertext );

} else {

sFootertext .out.println(“Footer text is incorrect. Actual Footer text is  ” + sFootertext );

}

]]>
/selenium/selenium-webdriver-insert-verification-point/feed/ 0
Selenium WebDriver – Methods /selenium/selenium-webdriver-methods/ /selenium/selenium-webdriver-methods/#respond Fri, 21 Oct 2016 13:52:15 +0000 /?p=671 While working with Selenium we need to use Java as well as Selenium WebDriver functions. WebDriver provides various methods to perform different actions on Web elements.

Common Selenium WebDriver Methods

Common elements methods for UI interaction

The following lists show details of some of the methods that selenium provides to perform actions on different web elements (listbox, editbox, checkbox, radio button) depending upon their type.

Method Purpose
Clear() Clears all of the contents if the elements is a text entity.
Click() Simulates a mouse click on the element.
getAttribute(String Name) Returns the value associated with the provided attribute name if present or null if not present.
getTagName() Returns the tag name of element.
getText() Returns the visible text contained within this element (including sub elements) if not hidden via CSS.
getValue() Gets the value of the element’s “value” attribute.
isEnabled() Returns true for input elements that are currently enabled otherwise false.
isSelected() Returns true if the element (like radio button, check box) is currently selected, otherwise false.
sendKeys(CharSequence…) Simulates typing into an element.
setSelected() Select an element (like radio button, check box, options within a select)
Submit() Submits the same block if the elements is a form or contained within a form. Blocks until new page is loaded.
toggle() Toggles the state of a checkbox element.

getAttribute is  one of the most common methods used specifically to get property values and used to verify data in the fields.

Search elements methods

WebDriver also provides two methods allowing you to search for elements within the current page’s scope:

Method Purpose
findElement(By by) Finds the first element located by the provided method (based on different location type)
findElements(By by) Finds all elements located by the provided method

Select web elements methods

WebDriver provides a support class named Select to simplify interaction with select elements and their association options. It is mostly used with elements of type list boxes.

Method Purpose
selectByIndex(int index)/

deselectByIndex(int index)

Select/deselect the option at the given index
selectByValue(String value) /

deselectByValue(String value)

Select/ deselect the option that has a value matching the argument.
selectByVisibleText(String text)/

deselectByVisibleText(String text)

Select/deselect the option that displays text matching the argument.
deselectAll() Deselects all options
getAllSelectedOptions() Returns a List<WebElement> of all selected options
getFirstSelectedOption() Returns a WebElement representing the first selected option.
getOptions() Returns a List<WebElement> of all options
isMultiple() Returns true if this is a multi-select list, otherwise false

Interacting with Rendered Elements

If you are driving an actual browser such as Firefox, you also can access a fair amount of information about the rendered state of an element by casting it to RenderedWebElement. This is also how you can simulate mouse-hover events and perform drag-and-drop operations.

WebElement element = driver.findElement(By.id(“header”));

RenderedWebElement renderedElement = (RenderedWebElement) element;

RenderedWebElement Methods
Method Purpose
dragAndDropBy(int moveRightBy, int moveDownBy) Drags and drops the elements moveRightBy pixels to the right and moveDownBy pixels down. Pass negative arguments to move left and up.
dragAndDropOn(RenderedWebElement element) Drags and drops the element on the supplied elemnt.
getLocation() Returns a Java.awt.Point representing the top left-hand corner of the element.
getSize() Returns a Java.awt.Dimension representing the width and height of the element.
getValueOfCssProperty(String propertyName) Returns the value of the provided property.
hover() Simulates a mouse hover event over the element.
isDisplayed() Returns true if the element is currently displayed, otherwise false.

WebDriver Methods

WebDriver methods are useful when you are working with the browser object itself and you would want to perform certain operations like close browser, get title of browser page, or if working with application which has multiple frames or web pop-up windows.

Method Purpose
close() Close the current window, quitting the browser if it’s the last window currently open.
get(Java.lang.String,url) Load a new Web page in the current browser window.
getCurrentUrl() Gets a string representing the current URL that the browser is looking at.
getPageSource() Get the source of the last loaded page.
getTitle() The title of the current page.
getWindowHandle() Return an opaque to this window that uniquely identifies it within this driver instance.
getWindowHandles() Return a set of window handles which can be used to iterate over all open windows of this webdriver instance by passing them to switchTo().WebDriver.Options.window()
manage() Gets the Option interface
navigate() An abstraction allowing the driver to access the browser’s history and to navigate to a given URL.
quit() Quits this driver, closing every associated window.
]]>
/selenium/selenium-webdriver-methods/feed/ 0
Selenium WebDriver – Creating First Script /selenium/selenium-webdriver-creating-first-script/ /selenium/selenium-webdriver-creating-first-script/#respond Wed, 19 Oct 2016 08:45:09 +0000 /?p=636 Recording and Exporting Script from IDE

We will record the test case using Selenium IDE and then export the test case using Java / JUnit 4 / WebDriver option. Follow the steps given below:

Step 1: Open Selenium IDE and verify that recording mode is ON

Step 2: Assuming that application Google search is already open in Firefox browser, Perform the following steps in IDE recording mode:

  • Search for an automationtutorial.com
  • Click on search button
  • Click on automationtutorial.com
  • Click on Selenium link in automationtutorial.com header

Step 3: Stop recording by clicking on Stop Recording button in record toolbar.

Step 4: Verify the steps below that recorded Selenium ID

Step 5: Select to File > Export Test Case As > Java / JUnit 4 / WebDriver

Step 6: Save it as MyFirstWebDriverTest in D:\Selenium folder. You will notice that the script is saved as MyFirstWebDriverTest.java file.

Step 7: Try to open the script you have saved in an editor like Eclipse.

Let us review the exported Java code. The exported test is Junit test. JUint is a unit testing framework for the Java programming language. We will see a class name “MyFirstWebDriverTest” shown in snapshot.

Configure Eclipse to Work with Selenium WebDriver

Step 1: Launch Eclipse from your location of eclipse.exe file.

Step 2: Open the default workspace, D:\SeleniumTest

Step 3: Click  on workbench icon (if you see default view)

Step 4: Go to File > Project > Java Project and enter as SeleniumTestAutomation

Step 5: Click on Finish

Step 6: Expand the project and select src folder

Step 7: Now we will create a new package which will contain all tests. Right click on the src folder. Select New > Package

Step 8: Name the Package as tests and click finish.

Step 9: Right click on this tests package and select New > Class, in the New Java Class dialog enter Name: MyFirstWebDriverTest.

Step 10:  Click finish.

Step 11: Open link http://www.seleniumhq.org/download/ and download Selenium Standalone Server jar file. Save the file in location D:\Selenium

Step 12: Select SeleniumTestAutomation in Eclipse, right click and select New > Folder

Step 12: Name the Package as tests and click finish.

Step 13: Go to the location where your workspace folder is stored. In our case it is D:\SeleniumTest\SeleniumTestAutomation. You will see Lib folder available. Double click to get in Lib folder.

Step 14: Copy selenium-server-standalone-3.0.1.jar file into the Lib folder which we had copied earlier in location D:\Selenium.

Step 15: Come back to Eclipse and click on your project and press F5. You should be able to see the Lib folder Jar file added to your project structure.

Step 16: Now Click on the Project > Properties and in opened window click on ‘Java Build Path’. Then Click the Libraries tab.

Step 17: Click on Add External Jars button and add selenium-server-standalone-3.0.1.jar file from D:\SeleniumTest\SeleniumTestAutomation\Lib

Step 18:  Click OK. Copy the code from the exported Selenium IDE script, MyFirstWebDriverTest.jave (open in notepad and copy) and Overwrite existing code of Eclipse in MyFirstWebDriverTest.java

You will notice the package name is throwing an error. This because currently our script is in different package named tests.

  • Make sure the package name is corrected to the right name of the package
  • Also make sure the class name is the same as the name of our newly created class in eclipse

Step 19: See below updated code after fixes

  • If you get any errors regarding classes not found then you have not imported the selenium jar correctly.
  • Make sure your JRE is not throwing an error. You can go to Project > Properties > Java Build Path and check the JRE is not throwing an error. If yes you can double click on JRE to select correct Java execution environment.

Running the Test

Now that we have configured our first WebDriver test let us run it and verify if it correctly executes. You have various options to run this Java code in eclipse. You can run it as:

  • A Java program using main method of a class.
  • Using JUnit Test Framework
  • using TestNG Framework

As part of this exercise we will run this script as JUnit script.

Project Clean-up

Before you run the script it is always good to clean up any existing .class file and re-build the project. To clean project files perform below steps:

Step 1: Select Project > Clean

Step 2: Select “Clean all projects” radio button on the Clean dialog box and click OK

Script Execution

There are two ways to execute code in Eclipse IDE.

  1. On Eclipse’s menu bar, click Run > Run or press ctrl+F11 to run the entire code.
  2. To execute your test, you right click script name in the project explorer and Run As > JUnit Test.

This will launch Firefox with the mentioned URL, perform your test steps.

]]>
/selenium/selenium-webdriver-creating-first-script/feed/ 0
Selenium Webdriver- Environment Setup /selenium/selenium-webdriver-environment-setup/ /selenium/selenium-webdriver-environment-setup/#respond Fri, 14 Oct 2016 13:27:16 +0000 /?p=598 To be able to use WebDriver for scripting, there are some pre-requisites that need to be in place like the basic environment setup. Users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps.

  • Download and Install Java
  • Download and Configure Eclipse
  • Configure Selenium WebDriver

Download and Install Java

Step 1: Navigate to the Oracle official site URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Step 2: Click on “Downloads” link and select “JDK Download”.

Step 3: Select “Accept License Agreement” radio button.

Step 4: Select the appropriate installation. Click the appropriate link and save the .exe file to your disk.

Step 5: Run the downloaded .exe file to launch the Installer wizard. Click ‘Next’ to continue.

Step 6: Select the appropriate features and click ‘Next’.

Step 7: The installer is extracted files and its progress is shown in the wizard.

Step 8: The user can choose/modify the install location and click ‘Next’.

Step 9: The installer installs the JDK and new files are copied.

Step 10: The Installer installs successfully and displays the same. Click the close button.

 

Step 11: To verify if the installation was successful, go to the command prompt and just type ‘java’ as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an “unknown command” error.

Download and Configure Eclipse

Step 1: Navigate to the URL: http://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture.

Step 2: Click the ‘Download’ button.

 

Step 3: The download would be in a Zipped format. Unzip the contents.

Step 4: Locate Eclipse.exe and double click on the file.

Step 5: To configure the workspace, select the location where the development has to take place.

Step 6: The Eclipse window opens as shown below.

Step 7: In Eclipse, select Windows > Preferences > Java -> Installed JREs

Step 8:  Make sure under the name field your jre checkbox should be checked.

Step 9:  Close the preferences dialog.

Step 10:  We are done with the one time setup.

Configure Selenium WebDriver

Download the Selenium Java Client Libraries

As we would be using Java as the programming language for this series and in order to create test scripts in java, we would have to introduce language- specific client drivers. Thus, let us begin with the downloading of Selenium Java Client Libraries.

Step 1: Navigate to the selenium downloads section http://www.seleniumhq.org/download/and download Selenium WebDriver by clicking on its version number as shown below.

Step 2: The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder.


Step 3: The Unzipped contents would be displayed as shown below.

Configuring Libraries with Eclipse IDE

Step 1: Open Eclipse by cli. Create a new java based project following File -> New -> Java Project. Refer the following figure for the same.

Step 2: Provide a user defined name for your Java Project. Let us provide the name as Selenium_Project and Click on the Finish Button. The newly created project can be viewed at the left side of the screen in the package explorer panel.

Step 3: Create a new Java class named as “First_WebdriverClass” under the source folder by right clicking on it and navigating to New -> class.

Step 4: Now let us configure the libraries into our Java project. For this, select the project and Right click on it. Select “Properties” within the listed options. The following screen appears, Select “Java Build Path” from the options.


Step 5: By default, “Libraries” tab is opened. If not, click on the “Libraries” tab. Then, click on the “Add External Jars…” button. Browse to the location where we have saved the extracted folder for Java Client Libraries.

Step 6: Select all the JAR files present in the “selenium-java-2.42.2” folder and click on open button within the dialog box. The properties dialog box should look like the below illustration.

Step 7: Click on the “OK” button within the dialog box so as to complete the configuration part of Selenium Libraries in our java project.

 

]]>
/selenium/selenium-webdriver-environment-setup/feed/ 0
Selenium – Basics of Java Part 3 /selenium/selenium-basics-of-java-part-3/ /selenium/selenium-basics-of-java-part-3/#respond Wed, 05 Oct 2016 12:31:22 +0000 /?p=587 Working with Classes, Objects and Methods

Declaring Classes – You have seen classes defined in the following way:

Class MyClass {

// field, constructor, and

// method declarations

}

This is a class declaration. The class body contains all the code that provide for the lifecycle of the objects created from the class.

In general, class declarations can include these components, in order:

  1. Modifiers such as public, private etc.
  2. The class name, with initial letter capitalized by convention
  3.   The name of the class’s parent if any, preceded by the keyword extends. A class can only extends one parent.
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implements more than one interface.
  5. The class body, surrounded by braces, {}

Declaring Member Variables – There are several kinds of variables:

  • Member variables in a class – these are called fields.
  • Variables in method or block of code – these are called local variables
  • Variables in method declarations – these are called parameters

Defining Methods or Functions

Here is an example of a typical method declaration:

public double calculateAns(double WingSpan, int numberOfEngine, double length) {

//do the calculation here

}

More generally, method declaration have six components, in order:

  1. Modifiers – such as public, private etc.
  2. The return type – the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name – the rules for field names apply to method names as well, but the convention is a little different.
  4. The Parameter list in parenthesis –  a comma-delimited list of  input parameters, preceded by their data types, enclosed by parentheses (). If there are no parameters you must use empty parentheses.
  5. An exception list – a comma-delimited list of exception
  6.  The method body, enclosed between braces – the method’s code, including the declaration of local variables, goes here.

Overloading Methods

The Java programming language supports overloading methods and java can distinguish between methods with different method signatures. This means method within a class can have the same name if they have different parameter lists.

public class DataArtist {

public void draw(String s) {

//write code here

}

public void draw(int i) {

//write code here

}

public void draw(double f) {

//write code here

}

public void draw(int i, double f) {

//write code here

}

}

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations – except that they use the name of the class and have no return type.

 

public class DataArtist {

public DataArtist() {

//write code here

}

public void draw(int i) {

//write code here

}

}

Returning a value from a method – A method returns to the code that invoked it when it

  • Completes all the statements in the method
  • reaches a return statement
  • throws an exception

whichever occurs first.

Using the this Keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Using this with a Field

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the constructor shadows one of the object’s fields — inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x, the constructor must use this.x.

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here’s another Rectangle class, with a different implementation from the one in the Objects section.

public class Rectangle {
private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}

}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle’s member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1×1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.

Exception Handling

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.

Exception Handling is a mechanism to handle run-time errors such as ClassNotFound, IO, SQL, Remote etc.

There are 5 keywords used in java exception handling.

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

To catch an exception we first put the code which we suspect to throw an error into a try block like

WebElement txtbox_username = driver.findElement(By.id(“username”));

try {

if (txtbox_username.isEnabled()) {

txtbox_username.sendKeys(“automation”);

}

}

catch(NoSuchElementException e) {

System.out.println(e.toString());

}

Followed by a catch block of code where we tell the system what should be done when the exception occurs. Generally this is where we display the message of the exception object so that we know which exception has occurred and why.

Multiple catch blocks – A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try {

file = new FileInputStream(filename);

x = (byte) file.read();

}catch(IOException I) {

i.printStackTrace();

return -1;

}catch(FileNotFoundException f) {

f.printStackTrace();

return -1;

}

The throws/throw Keywords

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.  You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Let us try to understand the difference in throws and throw keywords.

The following method declares that it throws a ArithmeticException. Since the exception is  not handled from within the code, we are using throw keyword to throw ArithmeticException.

The syntax of java throw keyword is given below.
throw exception;

public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[]){
validate(13);
System.out.println(“rest of the code…”);
}
}

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}

class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println(“normal flow…”);
}
}

Finally block

Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}

]]>
/selenium/selenium-basics-of-java-part-3/feed/ 0
Selenium – Basics of Java Part 2 /selenium/selenium-basics-of-java-part-2/ /selenium/selenium-basics-of-java-part-2/#respond Tue, 27 Sep 2016 13:45:22 +0000 /?p=575 Language and Syntax Basics

Variables

The Java programming language is statically-typed, which means that all variables must first declared before they can be used.

Example – int gear=1;

Data Type Default Value
Byte 0
Short 0
Int 0
Long 0L
Float 0.0f
Double 0.0d
Char \u0000′
String Null
Boolean FALSE

The Java programming language defines the following kinds of variable:

  • Instance Variables (Non-Static Fields)  – Variable declared without the status keyword called non-static fields and also known as instance variables. Example – object
  • Class Variables (Static Fields)A class variable is any field declared with the static modifier.
  • Local Variables – Similar to how an object stores its state in fields, a method will often store its temporary state in local variables.
  • Parameters – A parameter is a variable that is passed to a method when the method is called.

Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Example

Class Array {
public static void main(String[] args) {
//declares an array of integers
int[] intArray;
//allocates memory for 5 integers
intArray = new int[5];
//Initialize first element
intArray[0] = 50;
//Initialize second element
intArray[0] = 100;
//etc
SYstem.out.println(“Element at index 0:” + intArray[0]);
}
}

Similarly, you can declare arrays of other types:

byte[] arrayOfBytes;

short[]  arrayOfShorts;

long[]  arrayOfLongs;

String[]  arrayOfStrings;

//etc  (arrayVariable.length will return the size of array)

Operators

Operators are special symbols that perform specific operations on one, two or three operands, and then return a result. The following is a reference for operators supported by the java programming language.

Simple Assignment Operator

=  Simple assignment operator

Arithmetic Operators

+  Addition operator

–  Subtraction operator

*  Multiplication operator

/  Division operator

%  Remainder operator

Unary Operators

+    Unary plus operator

–      Unary minus operator

++  Increment operator

—    Decrement operator

!     Logical complement operator

Equality and Relational Operators

==  Equal to

!=   Not Equal to

>    Greater than

>=  Greater than or equal to

<     Less than

<=   Less than or equal to

Conditional Operators

&&  Conditional AND

||   Conditional OR

?     Ternary

Type Comparison Operator

instanceof    Compares an object to a specified type

Control Flow Statements

This section describes the decision-making statements (if, if-else, switch), the looping statements (for, while, do-while) and the branching statements (break, continue, return) supported by the Java programming language.

The If-elseif- else Statement 

if (condition A) { //do this }

elseif (condition B) { //do this }

else { //do this }

The control will go to one of the block of statements depending upon the given condition.

public class FlowControl {
public static void main(String[] args) {
int age = 14;
System.out.println(“Peter is ” + age + ” years old”);

if (age < 4) {
System.out.println(“Peter is a baby”);
} else if (age >= 4 && age < 14) {
System.out.println(“Peter is a child”);
} else if (age >= 14 && age < 18) {
System.out.println(“Peter is a teenager”);
} else if (age >= 18 && age < 68) {
System.out.println(“Peter is adult”);
} else {
System.out.println(“Peter is an old men”);
}
}
}

The switch Statement

In some cases you can avoid using multiple if-s in your code and make your code look better. For this you can use the switch statement. Look at the following java switch example

public class SwitchExample {
public static void main(String[] args) {
int numOfAngles = 3;

switch (numOfAngles) {
case 3:
System.out.println(“triangle”);
break;
case 4:
System.out.println(“rectangle”);
break;
case 5:
System.out.println(“pentagon”);
break;
default:
System.out.println(“Unknown shape”);
}
}
}

For Loop

for loop is very powerful and yet simple to learn. It is mostly used in searching or sorting algorithms as well in all cases where you want to iterate over collections of data. Here is a simple example of a “for” loop:

public class ForLoopExample {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
System.out.println(“Iteration # ” + i);
}
}
}

while Loop

The general form of the while loop can be expressed as follows:

while(condition) {
// execute code here
}

Condition is Boolean. This means until the condition is true the while loop will be executed. I will recreate our first example this time using while loop instead of for loop.

public class WhileLoopExample {
public static void main(String[] args) {
int i=0;
while(i<5) {
System.out.println(“Iteration # ” + i);
i++;
}
}
}

Do While Loop

The Java Programming language also provides a do-while statements, which can be expressed as follows:

do {

statement(s)

} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileLoopExample program.

public class DoWhileLoopExample {
public static void main(String[] args) {
int i=1;
do {
System.out.println(“Iteration # ” + i);
i++;
}while(i<5);
}
}

The Return Statement

The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn’t. To return a value, simply put the value after the return keyword.

Example – return count;

The data type of the returned value must match the type of the method’s declared return value. When a method is declared void, return doesn’t return a value or doesn’t have a return statement at all.

Java Keywords

The following list shows the reserved words in java. These reserved words may not be used as a constant or variable or any other identifier name.

abstract continue for new
switch assert default goto
package synchronized  boolean do
if private this break
double implements protected throw
byte else import public
throws case enum instanceof
return transient catch extends
int short try char
final interface static void
class finally long strictfp
volatile const float native
super while
]]>
/selenium/selenium-basics-of-java-part-2/feed/ 0
Selenium – Basics of Java Part 1 /selenium/selenium-basics-of-java-part-1/ /selenium/selenium-basics-of-java-part-1/#respond Thu, 22 Sep 2016 14:08:04 +0000 /?p=562 We will focusing on Java as a programming language in selenium WebDriver we need to be comfortable with the basics of Java. This topic we will discuss about basic concepts around Java language, Syntax for basic Java statements, exception handling and concept of classes and objects.

Key Objectives:

  • Object oriented programming concepts
  • Language and syntax basics
  • Object, classes and method
  • Exception Handling

Object Oriented Programming (OOPS) Concepts

Object

Objects are key to understanding object-oriented technology. Look around right now and you’ll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

These real-world objects share two characteristics: they all have state and they all have behavior. For example, dogs have state (name, color, breed, hungry) and dogs have behavior (barking, fetching, and slobbering on your newly cleaned slacks).

Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains its state in variables and implements its behavior with methods.

Definition: An object is a software bundle of variables and related methods.

Bundling code into individual software objects provides a number of benefits, including:

  • Modularity
  • Information hiding
  • Code re-use
  • Plug-ability and debugging ease

Class

A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.

A class in java can contain:

  • Data member (Fields)
  • Method
  • Constructor
  • Block

Example of Object and Class

class Student{
int id; //data member (fields )
String name;//data member(fields)

public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Inheritance

Inheritance refers to a feature of Java programming that lets you create classes that are derived from other classes. A class that’s based on another class inherits the other class. The class that is inherited is the parent class, the base class, or the superclass.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name  {
//methods and fields
}

Types of inheritance in java

Basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.


Example of Simple inheritance

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println(“Programmer salary is:”+p.salary);
System.out.println(“Bonus of Programmer is:”+p.bonus);
}
}

Abstraction

Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.

Abstract class – A class that is declared as abstract is known as abstract class. can have abstract and non-abstract methods (method with body). It needs to be extended and its method implemented. It cannot be instantiated.

  • Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
  • But, if a class has at least one abstract method, then the class must be declared abstract.
  • If a class is declared abstract, it cannot be instantiated.
  • To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Example
public abstract class Employee {
private String name;
private String address;
private int number;

public abstract double computePay();
// Remainder of class definition
}

Suppose Salary class inherits the Employee class, then it should implement the computePay() method as shown below

public class Salary extends Employee {
private double salary;   // Annual salary

public double computePay() {
return salary/52;
}
// Remainder of class definition
}

Interface

In its most common form, an interface is a group of related methods with empty bodies.

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways −

  • An interface can contain any number of methods.
  • An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
  • The byte code of an interface appears in a .class file.
  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including −

  • You cannot instantiate an interface.
  • An interface does not contain any constructors.
  • All of the methods in an interface are abstract.
  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
  • An interface is not extended by a class; it is implemented by a class.
  • An interface can extend multiple interfaces.

Example

interface Animal {

public void eat();

public void travel();

}

Package

A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage.

Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.

Method Overloading

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

Example

class Calculation {
void sum(int a,int b) {
System.out.println(a+b);
}

void sum(double a,double b) {
System.out.println(a+b);
}

public static void main(String args[]) {
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}

Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.

In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Example

class Vehicle{
void run(){
System.out.println(“Vehicle method”);
}
}

class Bike2 extends Vehicle{
void run(){
System.out.println(“Bike method”);
}

public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
}

Output: Bike method

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. Any Java object that can pass more than one IS-A test is considered to be polymorphic.

]]>
/selenium/selenium-basics-of-java-part-1/feed/ 0