August 26, 2015

Integrate AutoIT with Selenium Webdriver

In this post we will discuss about how to Integrate AutoIT with Selenium Webdriver.

Need of AutoIT in Webdirver:

Webdriver can only interact with web applications, it can not interact with desktop components or Browser related popups. 
Here are some of the situations where we need to take help of 3rd Party tools (Auto IT).

  1. File Uploads.
  2. Downloads.
  3. Handling User Authentications etc..

We will see below points:
1. What is AutoIT
2. Features of AutoIT
3. How to Install?
4. How to use?
5. Integrate AutoIT and Webdriver

What is AutoIT and Features :

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying “runtimes” required!


  • Easy to learn BASIC-like syntax
  • Simulate keystrokes and mouse movements
  • Manipulate windows and processes
  • Interact with all standard windows controls
  • Scripts can be compiled into standalone executables
  • Create Graphical User Interfaces (GUIs)
More details you can find here  --AutoIT Features

Install AutoIT:

To install AutoIt first download the AutoIt exe file from the below location.


1. Click on the topmost download for AutoIT
2. Follow the instructions to install AutoIT.


Record AutoIT script:
AutoIT has record feature. We can record script using AutoIT, for that we need AutoIT script Editor.

Download AutoIT Script Editor:
In Auto IT downloads page we have one more file called "Download Editor". Once you click on that it will navigte to downlaods page, then download "SciTE4AutoIt3.exe" file.

How to Use:

Scenario:
1. Navigate to http://www.dropzonejs.com/
2. Click on Try it Out section --It will open window (upload file window)
3. select a file and click open
4. Verify uploaded file in Try it Out section.



First lets see how to create AutoIT script to upload file.

If you want help about commands you can navigate to Start  > All Program > AutoIt v3  > Autoit Help file.  and search for commands.

In the above scenario i need to upload file. After clicking on try it Out it will open a Upload file window.
Need to identify Locators (text box).  AutoIt has given us Windows Info tool, it is same like Object Spy in QTP and Element Inspector in any Browser. To open it go to Start > All Program > AutoIt v3 > AutoIt Window Info.

Now drag the ‘Finder Tool‘ box to the object in which you are interested.


You can see that Windows Info tool has populated all the information which is required to use the method.

Write Automation script to Upload file:





Save that file with extension .au3 and Convert script to .exe file.



After compilation you will get Upload.exe file.

How to use file in Webdriver:


Runtime.getRuntime().exec("D:\downloads\Uplaod.exe");


Below is the code how to use Auto It in Webdirver:








August 25, 2015

ANT with Selenium Webdriver and TestNG (Selenium Ant TestNG)

In this article i would like to write something about Build tool ANT. http://ant.apache.org/

A build tool stores, executes automates all the process in a sequential order(Clean, SetPath, Compile and Execute) mentioned in Ant's build.xml file.


Benefits of ANT:

1. It is a simple build tool all configurations we can do from build.xml file.
2. Configuration is separate from application.
3. ANT is written in Java but its a platform independent tool. (Requires JDK)
4. We can create Jar files, Java doc.
5. Copy files to different locations
6. Can create directories and folders
7. Can create HTML reports.
8. It supports Junit4 and TestNG unit testing frameworks.

How to Setup ANT:

1. Download ant from  Download ANT





2. Unzip ant folder and place it in a folder (D:\ant)
3. Set ANT_HOME and Path in environmental variable.



4. Verify ANT. Open Command prompt and type in ant -version...shows you version of ANT.



Using ANT from Eclipse:

Download Sample ANT Selenium and TestNG 

project From Here..ANT-Selenium-TestNG


Folder Structure of Project Looks like this:



If you want to run ant from command prompt then use brlow command

1. Navigate to project directory
2. use command  --- ant run.

Below is build.xml file.




<project name="Experiment_Ant" basedir=".">

 <!-- Defining property -->

 <property name="project.dir" value="${basedir}" />
 <property name="build.dir" value="${basedir}/build" />
 <property name="jar.dir" value="${basedir}/lib" />
 <property name="src.dir" value="${basedir}/src" />
 <property name="ng.result" value="test-output" />

 <!-- Setting Classpath for jar files -->
 <target name="setClassPath">
  <path id="classpath_jars">
   <pathelement path="${basedir}/" />
   <fileset dir="${jar.dir}">
    <include name="*.jar" />
   </fileset>
  </path>
  <pathconvert pathsep=":" property="test.classpath" refid="classpath_jars" />
 </target>
 <!-- Loading Testng -->
 <target name="loadTestNG" depends="setClassPath">
  <taskdef resource="testngtasks" classpath="${test.classpath}" />
 </target>
 <!-- Deleting directories -->
 <target name="clean">
  <echo message="deleting existing build directory " />
  <delete dir="${build.dir}" />
 </target>
 <!-- Creating build folder to store compiled classes -->
 <target name="init" depends="clean,setClassPath">
  <mkdir dir="${build.dir}" />
 </target>
 <!-- Compiling java files -->
 <target name="compile" depends="clean,init,setClassPath,loadTestNG">
  <echo message="" />
  <echo message="compiling………." />
  <javac destdir="${build.dir}" srcdir="${src.dir}"
   includeantruntime="false" classpath="${test.classpath}" />
 </target>
 <target name="run" depends="compile">
  <testng classpath="${test.classpath}:${build.dir}">
   <xmlfileset dir="${basedir}" includes="testng.xml" />
  </testng>
 </target>

</project>

August 18, 2015

Create a Sample Maven Project

In this post i would like to discuss about Maven.

Here are few basic questions:

What is Maven?
What are the advantages of Maven.
How to use Maven in Selenium projects.
How to Create a maven project?


What is Maven:
Maven -- is a build tool and it is mainly used for Java projects. 
Maven is used to manage dependencies.
For example if you are using selenium latest version 2.47.1 and later point of time if you have to upgrade to newer version of selenium, then it can be manged very easily by using Maven dependencies.

What are the advantages of Maven.

It is a build tool, so it is used to setup everything which is required to run your java code independently.

Maven provides pom.xml which is core to any project.

Maven is used to manage dependencies.

Maven is a plugin for many of IDEs. (Eclipse, Netbeans, IntelliJ etc..)


Frequently used terms in Maven:

GroupID:
Group id refers to domain ID. For example you can use company name as groupID.

Artifact ID:
Name of the project. what ever the name you provide in artifact ID it is nothing but your project ID.

Local repository:

Maven downloads all required jar files and stores in local repository with folder name .m2 (C:\Users\username\.m2)


Maven Set Up:

Pre-requisites:
Make sure Java is installed
Make sure Java_Home and path are set under environmental properties.
Latest version of eclipse (Luna or Mars)

If you are using Luna or Mars you need not to install Maven plug in, bcs maven plug in is already installed in these versions of Eclipse EclipseIDE 


Verify Maven is already installed or not.
1. Open Eclipse, Click on Help ----> select About Eclipse..a window will open.

if you see m2 symbol there ..that means maven is installed.




Create Maven Project:

1. File ---New --Other ---Expand Maven and select Maven Project



2. Click Next in "New Maven Project Screen"

3. select "maven-archetype-quickstart" from list of artifacts. (be default quickstart will be selected)
4. Enter Group ID, Artifact ID Click Finish

5. Once you created a project in eclipse you can see the project




Add Dependencies:

Open pom.xml
Click on pom.xml tab
Add a testNG dependency.

  1. Navigate to MavenRepository and search for TestNG
  2. Select the desired version.
  3. Copy testNG dependency and paste it in pom.xml



4. Add Selenium related dependencies.

http://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java/2.47.1


org.seleniumhq.selenium
selenium-java
2.47.1



org.seleniumhq.selenium
selenium-server
2.47.1

Allow some time to download those Jar files and these files will be automatically added to your project. Files will be stored under .m2 folder (C:\Users\username\.m2)

Now you can write your normal Selenium-TestNG program and run the script.





If you want to run test case from maven you need below dependencies:
Pre requisite: Create a testNG test suite. 


Add below plugins to POM.xml

  1. maven-compiler-plugin
  2. maven-surefire-plugin
  3. testng.xml
The maven-surefire-plugin is used to configure and execute tests. Here plugin is used to configure the testing.xml for TestNG test and generate test reports.

The maven-compiler-plugin is used to help in compiling the code and using the particular JDK version for compilation. Add all dependencies in the following code snippet, to pom.xml in the node

Maven-Compiler-plugin:

http://maven.apache.org/plugins/maven-compiler-plugin/usage.html

Maven-sure-fire plugin:
http://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html


To run your test cases:

Right click on POM.xml--Run As ---mvn test

scripts which are in testNG.xml will be executed and results will be available under:
Project---target---surefire--report






POM.xml looks like this:










August 13, 2015

Introduction To Jenkins (Continuous Integration Tool)

In this post i would like to give some information what ever i know about Jenkins.

Frequently asked questions :

What is Jenkins?
What is Continuous Integration?
How to set up Jenkins?
Jenkins is it only for Developers or can testers also use it?
I am a Automation tester how can i use Jenkins?
What benefits / advantages i will get after using Jenkins?

In this article i am going to answer all the above questions...

What is Jenkins?

A simple answer every body gives to this questions is .... Jenkins is a Continuous Integration tool.

Jenkins is an open source tool to perform continuous integration. The basic functionality of Jenkins is to execute a predefined list of steps based on a certain trigger.

You can get more information about Jenkins here ...

About Jenkins

What is Continuous Integration? (CI)
CI is nothing but running your tests (unit tests /automation tests) automatically every time someone pushes new code into the source repository.

Ex:
If you are an automation tester and when you push some code to your source repository (SVN, GIT etc..) then your automation test cases will run automatically (if you configure like that) and will give you results. It gives you fast feed back about your test suite.

The fast feedback is important so you always know right after you broke the build . What you did that failed and how to revert it.

What benefits / advantages i will get after using Jenkins?
There are many advantages
1. When it is run automatically on every push then it is always pretty obvious what and who introduced the problem
2. Solves problems quickly
3. Automation of deployment.
4. Automated testing and Code control
5. Enables better project Visibility

Jenkins is it only for Developers or can testers also use it?

Jenkins is not only for developer even automation tester also can use Jenkins to test their automation scripts after each commit made by a team member or they can schedule their automation jobs to run daily at specific time.

How to set up Jenkins?

Coming soon...

I am a Automation tester how can i use Jenkins?

Coming soon...

August 10, 2015

How to Use Explicit Wait in Selenium Webdriver

Here is another post which will explains you about Explicit wait.

Below is the definition of explicit wait from selenium docs:

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

In simple words...you can use explicit wait where Implicitwait doesnt work. Ex: For Ajax elements, dynamically loading elements Implicit wait will not work. To handle Ajax and Dynamically loading elements we have to use Explicit wait.


In Below example

After clicking Start button it will take some time get text "Hello World"

we have to wait until that text present / wait until the element loads.


Here is explicit wait example...






Explicit wait has so many options...

Below are some of the options in ExpectedConditions...



Here is the Code:






package sample;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Explicitwait_Test {
 public WebDriver driver;
 public WebDriverWait wait;

 @Test
 public void testExplicitwait_Test() throws Exception {

  driver.get("http://the-internet.herokuapp.com");
  driver.findElement(By.linkText("Dynamic Loading")).click();
  driver.findElement(By.linkText("Example 1: Element on page that is hidden")).click();
  driver.findElement(By.xpath("//div[@id='start']/button")).click();
//  Explicit wait --wait until element visible
  wait = new WebDriverWait(driver, 10);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='finish']/h4")));
  String msg=driver.findElement(By.xpath("//div[@id='finish']/h4")).getText();
  System.out.println("Message is : "+msg);
  
 }

 @BeforeClass
 public void beforeClass() {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 }

 @AfterClass
 public void afterClass() throws Exception {
  driver.quit();
 }

}

August 3, 2015

Check all check boxes and verify status of check box

One more example from dave haeffner's weekly tip...

The Problem

Checkboxes, an often used element in web applications. But how do you work with them in your Selenium tests? Intuitively you may reach for a method that has the word 'checked' in it -- like .checked? or .isChecked. But this doesn't exist in Selenium. So how do you do it?

A Solution

There are two ways to approach this -- through an element's 'checked' attribute (a.k.a. an attribute lookup), or by asking the element if it is selected.
boolean org.openqa.selenium.WebElement.isSelected()

  • isSelected

    boolean isSelected()
    Determine whether or not this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
    Returns:
    True if the element is currently selected or checked, false otherwise.
Below example shows you how to check all check boxes and verify the status of check boxes.




package sample;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Checkboxes_Test {
 public WebDriver driver;

 @Test
 public void testCheckboxes_Test() throws Exception {

  driver.get("http://the-internet.herokuapp.com");
  driver.findElement(By.linkText("Checkboxes")).click();
  //get all the check boxes in web page
  List<WebElement> cBox=driver.findElements(By.cssSelector("input[type='checkbox']"));
  for (int i = 0; i < cBox.size(); i++) {
   //verify check box status, if it is not checked then perform click operation
   if (!cBox.get(i).isSelected()) {
    cBox.get(i).click();
    System.out.println("Check box "+ i + " status is :"+cBox.get(i).isSelected());
   }
   else
   {
    System.out.println("Check box "+ i + " is already selected and status is :"+cBox.get(i).isSelected());
   }
  }
 }

 @BeforeClass
 public void beforeClass() {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 }

 @AfterClass
 public void afterClass() throws Exception {
  driver.quit();
 }

}

July 30, 2015

How To Test For Disabled Elements

Long back i saw some post from Dave Haeffner  and he is writer of Elemental Selenium -- a free, once weekly Selenium tip newsletter that's read by thousands of testing professionals, also the author of The Selenium Guidebook; a guide on how to use Selenium successfully.

I am receiving some weekly tips from Dave Haeffner's site and those are in Ruby language. i want to rewrite them in Java. Using Selenium webdriver + TestNg + Java

Problem:
On occasion you may have the need to check if an element on a page is disabled or enabled. Sounds simple enough, but how do you do it? 

Solution:
We have a available method called isEnabled(). which will help us in resolving the above problem.
boolean org.openqa.selenium.WebElement.isEnabled()


  • isEnabled

    boolean isEnabled()
    Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
    Returns:
    True if the element is enabled, false otherwise.


package sample;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Enable_test {
	public WebDriver driver;

	@Test
	public void testEnable_test() throws Exception {

		driver.get("http://the-internet.herokuapp.com");
		driver.findElement(By.linkText("Dropdown")).click();
		List<WebElement> dropdown=driver.findElements(By.xpath("//select[@id='dropdown']/option"));
		for (int i = 0; i < dropdown.size(); i++) {
			if(dropdown.get(i).getText()=="Please select an option")
			{
				//assert false will always expects false value. 
				//Here option is disabled so it will return false
				Assert.assertFalse(dropdown.get(i).isEnabled());
			}
		}
	}

	@BeforeClass
	public void beforeClass() {
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
	}

	@AfterClass
	public void afterClass() throws Exception {

		driver.quit();
	}

}