Buy From Flipkart

Friday, 14 February 2014

File Downlaoding using Selenium Webdriver

  File Downlaoding using Selenium Webdriver:

Files downloading using WebDriver is possible by using profile set up in FireFox. Following is the sample code for setting preferences , The important aspect to go with downloading is you need to know the MIME type of the file that you wanted to download.

For Example if you wanted to download .txt (i.e text file) file then you need to add text/plain in the browser.helperApps.neverAsk.saveToDisk preference saveToDisk is the profile preference which excludes windows popup of Open with / save .

you can find the MIME types for different file type in the following link  

Following is the sample code snippet  for file downloading

       FirefoxProfile profile = new FirefoxProfile();
        String path="d:\\downloads123";
        profile.setPreference("", 2);
        profile.setPreference("", path);
        profile.setPreference("", false);
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/csv,text/csv,image/png ,image/jpeg, application/pdf, text/html,text/plain,application/octet-stream");
        WebDriver driver = new FirefoxDriver(profile);

Please do comment hear if you have any queries on this topic.

Please do comment for any queries

Friday, 7 February 2014

Selenium WebDriver : Implicit Wait Vs Explicit Wait Vs Custom-expected Wait

Using Selnium 2 (i.e WebDriver) we have number of ways for implementing WaitForAnElement, In this post will try to explain them with an example.

WaitForElement with an implicit wait :

The Selenium WebDriver provides an implicit wait for synchronizing tests. When an implicit
wait is implemented, if WebDriver cannot find an element in the Document Object
Model (DOM), it will wait for a defined amount of time for the element to appear in the DOM.

Once set, the implicit wait is set for the life of the WebDriver object's instance. However, an
implicit wait may slow down your tests when an application responds normally, as it will wait
for each element appearing in the DOM and increase the overall execution time.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Until the end of a test or an implicit wait is set back to 0, every time an element is searched
using the findElement() method, the test will wait for 10 seconds for an element to appear.

WaitForElement with an explicit wait:

The Selenium WebDriver also provides an explicit wait for synchronizing , which provides
a better control when compared with an implicit wait. Unlike an implicit wait, you can write
custom code or conditions for wait before proceeding further in the code.

An explicit wait can only be implemented in cases where synchronization is needed and the
rest of the script is working fine.

The Selenium WebDriver provides WebDriverWait and ExpectedCondition classes for
implementing an explicit wait.

The ExpectedCondition class provides a set of predefined conditions to wait before
proceeding further in the code. The following are some common conditions
that we frequently come across when automating web browsers supported by the
ExpectedCondition class:

An element is visible and enabled          elementToBeClickable(By locator)              
An element is selected                          elementToBeSelected(WebElement element)
Presence of an element                         presenceOfElementLocated(By locator)        
Title                                                    titleContains(java.lang.String title)                  

WebDriverWait wait = new WebDriverWait(driver, 10);
 Next, ExpectedCondition is passed to the wait.until() method as follows:

The WebDriverWait object will call the ExpectedCondition class object every 500
milliseconds until it returns successfully.

WaitForElement with custom-expected conditions :

The Selenium WebDriver also provides a way to build custom-expected conditions along with
common conditions using the ExpectedCondition class.

The Selenium WebDriver provides the ability to implement the custom ExpectedCondition
class along with the WebDriverWait class for creating a custom-wait condition, as needed
by a test. In this example, created a custom condition, which returns a WebElement
object once the inner findElement() method locates the element within a specified
timeout as follows:

WebElement message = (new WebDriverWait(driver, 5))
.until(new ExpectedCondition<WebElement>(){
public WebElement apply(WebDriver d) {
return d.findElement("qaautomationworld"));

Other popular posts:

Wednesday, 5 February 2014

Installing m2eclipse – Maven Plugin for Eclipse

In this tutorial, we will see how to install m2eclipse plugin which provides Maven integration in Eclipse IDE.

Before installing eclipse plugin in ellipse. its better to install maven in your machine  look at this post Maven installation

Environment Used

  • Java SE 6
  • Eclipse Juno for Java EE Developers  IDE
  • Maven Eclipse Plugin – m2eclipse version 1.2

    Before going forward make sure you have set the JDK path as JAVA_HOME in your environmental variables.


Online Installation (From Update Site) of Maven Plugin m2eclipse:

Step 1:

Installing m2eclipse is fairly simple. Start Eclipse then go to:
Help -> Install New Software…
Copy this link for the latest Stable Release into Eclipse and hit Enter.

When the site loads, select the features to install, or click the Select All button. For our requirement select “Maven Integration for Eclipse” as shown above.
Checking [x] Contact all update sites during install to find required software might take sometime and this is optional.

Step 2:

  • Click Next to view Installation Details.
  • Click Next to agree the license terms, and click Finish.

Step 3:

If you get any warning message when installing, click OK to continue.

This will take few minutes to install the Maven plugin and once done restart the Eclipse.

Creating New Maven Project in Eclipse

After installing the Maven plugin for Eclipse, you can check if the installation is successful by creating a new Maven project.
You should see a Maven folder in the New project wizard as shown below

Now you have successfully installed “Maven plugin – m2eclipse” in Eclipse IDE.

Other popular posts:

How to install Maven on Windows

All possible ways for handling DragAndDrop using Selenium

All Possible ways for switching frames in Selenium

Automating tables tags using Selenium

Selenium Webdriver Integration with JBheave (BDD)

How to install Maven on Windows

Maven Installation is quite straight forward please have look at the following procedure and do comment if you get any issues while installing maven

Apache Maven is not require to install on Windows as a service component, you just need to download the Maven’s zip file, extract it and configure the Windows environment path variable.
Tools Used :
  1. JDK 1.6 or newer version
  2. Maven 2.2.1 or newer version
  3. Windows xp or  7

    1. JDK and JAVA_HOME

    Make sure JDK is installed, and “JAVA_HOME” variable is added in Windows environment variable, and point to the JDK folder.

    2. Download Apache Maven

    Visit this Maven official website, choose a version and click on the download link,

    3. Extract It

    Extract the downloaded zip file. In this case, we extracted to d driver and renamed the folder, e.g D:\mavenNote:
    That’s all, just folders and files, installation is NOT required on Windows.

    4. Add MAVEN_HOME

    Add a new "MAVEN_HOME" variable to the Windows environment, and point it to your Maven folder.

    5. Add PATH

    Update "PATH" variable, append “Maven bin folder” path, so that you can run the Maven’s command everywhere.

    6. Verification

    Done, to verify it, in command prompt, type “mvn –version“.

    If you see similar message, means your Apache Maven is installed successfully on Windows.

    Other popular posts:

    All possible ways for handling DragAndDrop using Selenium

    All Possible ways for switching frames in Selenium

    Automating tables tags using Selenium

    Selenium Webdriver Integration with JBheave (BDD)

Tuesday, 4 February 2014

Webdriver Integration with Jbehave (BDD)

JBehave is a framework for Behaviour-Driven Development (BDD). BDD is an evolution of test-driven development (TDD) and acceptance-test driven design, and is intended to make these practices more accessible and intuitive to newcomers and experts alike. It shifts the vocabulary from being test-based to behaviour-based, and positions itself as a design philosophy.

In this post i will be explaining, how to create sample Maven Jbehave project for Selenium.For this i am assuming that you have maven installed in your system and maven plugin for eclipse, if not you can have a look at this posts, this is pretty straight forward.

How to install Maven on Windows .

Installing m2eclipse – Maven Plugin for Eclipse

Creating Maven Jbeave project form the command line:

Execute following maven command in the command line

mvn archetype:generate -Dfilter=org.jbehave:jbehave

when you execute this command, maven will list out all the available of Jbehave atchetypes(simple project, groovy, web e.t.c)
As an example i am entering 5 (i.e Jbehave-Simple-archetype) as a input.

Then cmd line will ask for entering groupid .
what is groupid?
    groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.
eg. org.apache.maven, org.jbehave.selenium

I am entering com.jbehave.selenium

Then cmd requests for artifactid

What is artifactid?
is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.
  •      eg. maven, jbehave-selenium

I am entering jbehave-selenium

Then cmd requests for versionwhat is version?
     version if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.

Then cmd requests for package enter , after entering the package name cmd requests for Confirm properties configuration: where you need to enter Y

And finally you will getting a conformation message that Build Success as like bellow.

Configuring maven setup form the command line:

After creating the maven project you need to configure this project with the eclipse . For that you need to add the eclipse resource (jars) in order to do that we need to execute the following command by navigating to the maven project ( In our example i need to navigate to
jbehave-selenium i.e artifactid )

mvn eclipse:eclipse

Open the Project in Eclipse :

Now Jbehave Maven project is created , open the eclipse set the workspace as created project's parent directory( In my case i have created the project in C:\Document and Settings\smedarapu\jbejave-selenium , so i am setting workspace at C:\Document and Settings\smedarapu )Now in eclipse click on New --> Other ---> java --> java project-->Next then enter the project name what you have created (in my case it is jbehave-selenium ), Finally click on Finish .

Then project will be opened with the default code and in the following structure.

Now open the pom.xml file and add the selenium dependency under the <dependencies> tag

Selenium maven dependency:
Now will try to look at the coding part

Open the  my.story file and replace existing content with following content

Scenario: A sample scenario for Jbeahve with selenium

Given I am in FF
And I navigate to google
Then I verify search field

in the add the following code

import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Pending;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MySteps {
    static WebDriver driver;
    @Given("I am in FF")
    public void invokeBrowser()
         driver = new FirefoxDriver();
    @Given("I navigate to google")
    public void navigate()
    @Given("I verify search field")
    public void verify()
    {// verifying search element in google home page

Now right click on pom.xml Run As--> Maven Clean then Run As --> Maven install , you can see the test cases execution starts where the FF invoke then navigates to the google finally search for the searchfield in google field .

How it works...

For creating tests in JBehave, we will need to first implement stories as the .story file using
the Given, When, and Then structures. We need to  describe the purpose of the story in the Scenario section, which contains the actual steps. We also
pass the required test data from these steps:

Scenario: A sample scenario for Jbeahve with selenium

Given I am in FF
And I navigate to google
Then I verify search field

Next, we map these steps using a step definition class(i.e in MySteps ).

For each step, we use an annotation and implement a method to run that step. For example,
for the step Given I am in FF we have defined the invokeBrowser()
method as follows:

@Given("I am in FF")
    public void invokeBrowser()
         driver = new FirefoxDriver();
Along with a story file and a step definition class, a Configuration class needs to be
created, which will be based on the JUnitStory class from the JBehave framework:
public abstract class MyStories extends JUnitStory

It also provides other configuration information, like the location of the story files and report
settings, and format the JBehave framework. In this case, the .story files will be located
using the path of the story or step definition classes:
    public Configuration configuration() {
        Class<? extends Embeddable> embeddableClass = this.getClass();

        // Start from default ParameterConverters instance
        ParameterConverters parameterConverters = new ParameterConverters();

        // factory to allow parameter conversion and loading from external resources (used by StoryParser too)
        ExamplesTableFactory examplesTableFactory = new ExamplesTableFactory(new LocalizedKeywords(), new LoadFromClasspath(embeddableClass), parameterConverters);

        // add custom converters
        parameterConverters.addConverters(new DateConverter(new SimpleDateFormat("yyyy-MM-dd")),
                new ExamplesTableConverter(examplesTableFactory));
        return new MostUsefulConfiguration()
            .useStoryLoader(new LoadFromClasspath(embeddableClass))
            .useStoryParser(new RegexStoryParser(examplesTableFactory))
            .useStoryReporterBuilder(new StoryReporterBuilder()                .withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))
                .withFormats(CONSOLE, TXT, HTML, XML))
We used the JUnitStory class so that we can execute these tests with JUnit Test Runner.
At the end of the execution, JBehave generates an HTML report with a detailed status of the
stories executed, stories passed, or failed.