Cucumber Background Tutorial

When writing multiple scenarios in a Feature file we can easily end up writing the same ‘introductory’. However we can reduce the duplication using Cucumber Background. Let’s have a look at how we can use Cucumber Background to run common steps.

Cucumber Background

Lets have a look at a Feature file with multiple Scenarios which use similar steps:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the Java WebDriver tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Java WebDriver Tutorial" page
Then the page title should be visible

Scenario: To check that the Java Cucumber tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Java Cucumber Tutorial" page
Then the page title should be visible

Scenario: To check that the Git tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Git Tutorial" page
Then the page title should be visible

If you have a look at the above Scenarios then you can see that we repeat the same ‘Given’ step across all Scenarios. This means that if we have to write more Scenarios then we will end up writing the same test step for each Scenario. This is where we can reduce running the same test steps via Cucumber Background. Lets have a look at how we can use Cucumber Background to help us:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Background:
Given I navigate to TheTestRoom.com

Scenario: To check that the Java WebDriver tutorial main page has loaded
Given I navigate to "Java WebDriver Tutorial" page
Then the page title should be visible

Scenario: To check that the Java Cucumber tutorial main page has loaded
Given I navigate to "Java Cucumber Tutorial" page
Then the page title should be visible

Scenario: To check that the Git tutorial main page has loaded
Given I navigate to "Git Tutorial" page
Then the page title should be visible

The Background section in a Feature file is designed to run test steps before each Scenario in the Feature file. For instance in the above Feature file the Background section will run before every Scenario. This means every Scenario will automatically run the ‘Given’ step for each Scenario.

And that’s it. In this tutorial we have learned how to use Cucumber Background and apply it to a Feature file. We have seen how the Background script can be used to reduce test step duplication and also increase Feature file management.

Video Tutorial on YouTube

cucumber background

Direct Video Link

Cucumber Datatable Tutorial

When we pass in parameters into a Step Definition then we can only pass in a single value however we can overcome this issue and pass in chunks of data via Cucumber DataTable. We can use Cucumber DataTable to pass in an array of information in a single step.

Using Cucumber Datatable

Let’s have a quick look at how we can pass in a single value via a test step in a Feature file and into a Step Definition method:

Feature File:

When I click on "Cucumber Java Tutorial"

Step Definition:

@When("^When I click on \"([^\"]*)\"$")
public void iClickOn(String link){
//code here
}

We can see that in the above Feature file we are passing in a single String value from the Feature file and into the Step Definition method. However in this current context we are not able to pass in a chunk of data. To put it slightly differently when using Cucumber Parameters it is not possible to pass in ‘arrays’ of information. This is where we can apply Cucumber DataTable policy. Cucumber DataTable can be used to pass in arrays of information in a single step. Here is an example of where I use Cucumber DataTable:

Feature File:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com
  Scenario: To check that tutorial pages have loaded
    Given I navigate to TheTestRoom.com
    When I navigate to "Java WebDriver Tutorial" page
    Then the following links should be visible
      | Java Cucumber Tutorial |
      | Git Tutorial           |

Step Definition:

    @Then("^the following links should be visible$")
    public void the_following_links_should_be_visible(List linkData) throws Throwable {
        // List, List>, List> or Map.
        for (int i = 0; i < linkData.size(); i++) {
            System.out.println(linkData.get(i));
        }
    }

Looking at the above Feature file you can see that we are now passing in a table of data into a single step. If you look at the matching Step Definition then you can see that we are capturing that information in a List i.e. an array. When we pass in data in a Feature file in the above format then this allows us to pass in rows of information which in turn can be captured in an array in a Step Definition. This data in a Step Definition method is actually captured as a DataTable (a collection container in Cucumber) however we can cast it to be captured as a List or Map instead as part of the method signature. After we cast it to either a List of a Map, this makes it easier to work with in our Step Definition methods.

And that's it folks. In this tutorial we have learned how to pass in arrays of data from a Feature file and into a Step Definition method. We have seen how powerful this simple technique is as this gives another option to passing data in 'bulks' as opposed to single values.

Video Tutorial on YouTube

cucumber datatable

Direct Video Link

Cucumber Scenario Outline Tutorial

Passing parameters in Cucumber is a powerful feature but we can extend this by utilizing ‘Cucumber Scenario Outline’.

Cucumber Scenario Outline

When writing Scenarios in Feature files it is always ideal to write specific Scenarios as to ensure that they make sense and bring value. For instance if we take the following example:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the Java WebDriver tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Java WebDriver Tutorial" page
Then the page title should be visible

Then we can see that the Scenario is very specific. If you want to write more Scenarios around checking ‘page load’ for other pages then you should have a Scenario for each page:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the Java WebDriver tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Java WebDriver Tutorial" page
Then the page title should be visible

Scenario: To check that the Java Cucumber tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Java Cucumber Tutorial" page
Then the page title should be visible

Scenario: To check that the Git tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "Git Tutorial" page
Then the page title should be visible

Looking at the above Feature file you can easily see that the Feature file contains three Scenarios. Although there are multiple Scenarios we also take advantage of passing in parameters as to reduce the number of step definition methods that we need to write. If you look through all three Scenarios then you should be able to see that the test steps between all three Scenarios are very similar, the only difference being the parameter. With this in mind it does feel like we are repeating ourselves a lot here since the Scenarios are pretty much the same. For instances such as this were the Scenarios are very similar with the exception being the parameters that are passed in, we can use Cucumber Scenario Outline to pass in multiple parameters into a single Scenario.

Using Cucumber Scenario Outline

Cucumber Scenario Outline look very similar to Scenarios but the only different is that the parameter which we pass in don’t sit in the Scenario itself but instead in an ‘Examples’ table directly below the Scenario. If we convert the above three Scenarios to instead use a Scenario Outline then this is what it would look like:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario Outline: To check that the Java WebDriver tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to "<page>" page
Then the page title should be visible
Examples:
|page|
|Java WebDriver Tutorial|
|Java Cucumber Tutorial|
|Git Tutorial|

So what is happening in the Feature file above? There are a number of differences in the Scenario Outline Feature file above so lets go through them. If you notice instead of passing in an actual value in the ‘When’ step we are now passing in a reference to a ‘page’ parameter. The value of the ‘page’ is obtained from the ‘Examples’ table. In the previous Feature file we had three Scenarios but this has been condensed into a single Scenario Outline in this Feature file. Cucumber Scenario Outline works slightly differently as they run multiple times as opposed to Scenarios which run only the one time. When looking at the ‘Examples’ table the first row is used to identify the name of the parameter reference which we will use in the Scenario Outline. This means for each row other than the first row in an Examples table a Scenario Outline will run itself. This means since there are three data rows in the ‘Examples’ table the Scenario Outline will run three times where each time it run’s it will substitute the value of ‘page’ from the ‘Examples’ table.

Cucumber Scenario Outline really help to slim down having to write similar Scenarios and also help us to run the same Scenario Outline using multiple parameters. This is a great way of reducing Scenario duplication and also a way of managing better Feature files.

And that’s it for this tutorial folks.

Video Tutorial on YouTube

cucumber scenario outline

Direct Video Link

Cucumber Parameter Tutorial

Now that we have setup an IDE we can start to look at passing Cucumber parameters from a Feature file and into a step definition class. One of the features of a Feature file is the ability to pass a Cucumber Parameter to a step definition class. We can use this ability to help write better step definition methods which can cater for multiple test steps in a Feature file. What this means is that a number of test steps can now reference the same step definition method. Lets have a look at how we can achieve this.

How does a Test Step find a Step Definition

We have talked about how a Feature file actually finds a step definition class (via the glue parameter in Cucumber) but we have not talked about how a test step in a Feature file actually finds a matching step definition in a step definition class. When a Feature file has located a step definition class it uses Regex to match a test step in a Feature file to a step definition method in a step definition class. For the following test step ‘Given I navigate to TheTestRoom.com’ the text after the Gherkin keyword i.e. ‘I navigate to TheTestRoom.com’ is used as the String to match the Regex pattern in a step definition annotation. For instance:

Feature File:
Scenario: Check Cucumber Tutorial page has loaded
Given I navigate to thetestroom.com

And now the step definition:

@Given("^I navigate to thetestroom\\.com$")
public void navigateToTheTestRoom() {
// code here
}

If look at the text for the test step in the Feature file and the expected Regex pattern in the step definition, then you can see that they match. It is the line of text (or String) in the Feature file which is used by Cucumber to actually match a test step to a step definition method.

Regex Patterns to understand

Before we go into detail about how we actually match the text of a test step to a step definition, we need to gain a small understand of Regex patterns used by Cucumber. First of all what is Regex? Regex is a pattern tool which is used to match Strings across any text based documents. We can use Regex to define patterns which we can then use to scan entire documents to help find matching strings. Regex has a number of ways to match Strings but the functions which we are most interested in are listed below:

^ - This marks the beginning of the string
$ - This marks the end of the string
\ - This is used to allow using special characters in a Regex pattern such as " and .
* - This is used to mean either zero, one of more
( ) - The text in these brackets are used to identify grouped characters
[ ] - This text is in these square brackets are used to match a single character using an or expression
. - This text will be used represent any character

Using the above we can combine some of the syntax to get certain types of results. For instance:

^Navigate to thetestroom$ - This will look for an exact match of the String 'Navigate to thetestroom'
^I navigate to thetestroom\\.com$ - This will look for an exact match of the String 'Navigate to thetestroom.com'
^I .* to thetestroom\\.com$- This will look for an exact match of the String 'Navigate to thetestroom.com'

Regex has many more features and methods which allow someone to match Strings but the functions above are enough to get us started with Cucumber. We will be using the above Regex functions to help us match the text in a test step against a step definition method.

Passing Cucumber Parameter

Now that we have gained a simple understand of Regex, lets have a look at how we can pass a Cucumber Parameter from a Feature file and into a step definition class.

We can capture specific sections in a test step to pass as a Cucumber parameter in a a Feature file. I usually do this using double quotation marks in a test step to make it easier for me to capture the parameter which I am about to send. This is also good practice as Cucumber Feature files highlight this as a parameter:

When I click on "Cucumber Java Tutorial"

And in the step definition method we can use Regex to capture all the text in the double quotation marks which we pass from the Feature file like so and capture in a step definition method:

@When("^When I click on \"([^\"]*)\"$")
public void iClickOn(String link){
//code here
}

If you have a look at the above step definition method then you should be able to see that we are able to capture any parameter that we pass from a Feature file test step and into a Step Definition class step definition method. We can then use these parameters to create step definitions which we can use for multiple test steps. This means we can now do the following:

When I click on "Cucumber Java Tutorial"
When I click on "WebDriver Java Tutorial"
When I click on "AngularJS Java Tutorial"

All three above steps can now be used to refer to the same step definition as all the text in each test step now matches the regex pattern in the same step definition method.

And that’s it folks. In this tutorial we have looked at how to pass a Cucumber Parameter from a Feature file and into a step definition class. Using this information we can now easily pass a Cucumber Parameter and really start to take advantage of the power of Cucumber.

Video Tutorial on YouTube

cucumber parameter

Direct Video Link

Cucumber Maven Eclipse Setup Tutorial

With basic WebDriver and Cucumber script writing tutorials now covered we will look at Cucumber Maven Eclipse setup. We will look at setting up Cucumber using Maven and we will do this through an Eclipse. Cucumber Maven Eclipse setup should lay foundations for many blog tutorials in this course.

01 Cucumber Maven Eclipse Setup

What is Maven? Maven is a build tool which can be used to build projects and manage their dependencies. What this means is that Maven can be used to automatically download jars for a given Java project without the user having to manually download any. It makes it more easier and manageable when building and maintaining projects. To date we have been manually download our jars from websites such as Selenium and Maven Repository but with Maven all of that is taken care of automatically.

02 IDE Installation

What is an IDE? An IDE (Integrated Development Environment) is the technical term given to a product which allows someone to write code or scripts through a user interface. An IDE can also allow the same user to download plugins which allows further customization, for instance some IDE’s do not support Cucumber straight out of the box but with the power of a plugins this can easily be remedied.

Eclipse is perhaps one of the most common IDE’s available to use, it is open source and very famous among both new and senior developers. There are other options such as IntelliJ but in this blog I am picking Eclipse simply because it’s simplicity and ease of use. Let go ahead and download Eclipse from https://eclipse.org/downloads/.

I am going to download ‘Eclipse IDE for Java Developers’. After your download completes then you should notice that the fully downloaded file is a zipped file. This means you will need an ‘unzipping’ program to unzip the file. Eclipse downloads are a little different as the file you have just downloaded is the whole applcation. Sorry if you were expecting an installer but luckily with Eclipse once you unzip the folder all you have to do is copy the unzipped folder to a location of your choosing. I personally will move it to my C: driver. Which ever location you chose, open the folder and start Eclipse by double clicking on the Eclipse application icon.

If Eclipse opens then you have completed your IDE installation. At the time of writing this blog the version of Eclipse IDE for Java Developers is Mars.2 Release (4.5.2).

03 Getting Cucumber to work with Eclipse

The first thing we need to do is install a Cucumber plugin to help us write Feature files for Eclipse although a plugin is strictly not needed to write Feature Files in Eclipse. To add the plugin select ‘Help’ from the main menu and select ‘Install New Software’. Once the window opens click on the ‘Add’ button from the top right and enter the following:

Name: cucumber
Location:  http://cucumber.github.com/cucumber-eclipse/update-site

Click ‘OK’ to add the plugin to your plugin list. Select ‘Cucumber Eclipse Plugin’ from the newly generated list and hit the ‘Next’ button until the plugin is installed. Accept any warnings which may display and once the plugin is installed Eclipse will perform a restart. The version of the plugin at the point of time when writing this blog is ‘0.0.15.201605080636’. This is one of the first steps towards Cucumber Maven Eclipse setup.

With the plugin installed lets go ahead and create a brand new Maven project. To do this select ‘New’ from the top bar menu and select ‘Other’. When the ‘New Wizard’ window opens type in Maven into the filter box and select ‘Maven Project’. This will display the New Maven project windows. Lets go with the default settings for now. When Group Id and Artifact Id are displayed type in com.thetestroom for the Group Id and cucumber_project for the Artifact Id and click ‘Finish’. This should have now created your Maven project.

With the project window opened (if it is not then ensure all other Eclispe windows are closed such as the ‘Welcome’ window) right click on src/test/java/com.thetestroom/cucumber_project and select ‘new’ and then ‘file’. In the file dialog box set the file name to myFirstFeature.feature. Notice that this creates a Feature File which Eclipse recognizes. Copy in the following contents into the Feature File:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the WebDriver Cucumber tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to Cucumber Tutorial page
Then the page title should be visible

Once done right click inside the Feature File and select ‘Run As’ and then ‘Cucumber Feature’. As you are able to see the option to run a Feature File as Cucumber Feature then this proves that your Eclipse is now configured to run Feature Files. This is great. After running your Feature file you should see the output below:

Error: Could not find or load main class cucumber.api.cli.Main

This means that you don’t have the required files yet for this Cucumber Maven Eclipse setup. To do this we need to add dependencies into the pom.xml file. In previous tutorials we used to copy in the Jars manually but with Maven we don’t have to do any of this since Maven will automatically download the jars and place them in the Classpath. This is what makes Maven so powerful. Copy in the following dependencies below into your pom.xml file:


     info.cukes
     cucumber-jvm-deps
     1.0.5


     info.cukes
     gherking
     2.12.2


     info.cukes
     cucumber-core
     1.2.4


     info.cukes
     cucumber-java
     1.2.4

Now right click on your Featiure file and run it as a Cucumber Feature and the output should be something like this:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the WebDriver Cucumber tutorial main page has loaded # C:/Users/MohammedShahin/workspace/cucumber_project/src/test/java/com/thetestroom/cucumber_project/myFirstFeature.feature:3
    Given I navigate to TheTestRoom.com
    When I navigate to Cucumber Tutorial page
    Then the page title should be visible

1 Scenarios (1 undefined)
3 Steps (3 undefined)
0m0.000s

You can implement missing steps with the snippets below:

@Given("^I navigate to TheTestRoom\\.com$")
public void i_navigate_to_TheTestRoom_com() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}
@When("^I navigate to Cucumber Tutorial page$")
public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}
@Then("^the page title should be visible$")
public void the_page_title_should_be_visible() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}  

Great, it looks like we have been able to get Cucumber to now fully work via Eclipse. Only a handful of tasks remain now to complete this Cucumber Maven Eclipse setup. First we need to create the Step Definition file so lets create a new Java class called myFirstStepDefinition under src/test/java/com.thetestroom/cucumber_project/ and copy in the contents as shown below:

package com.thetestroom.cucumber_project;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.java.en.*;

public class myFirstStepDefinition {
    WebDriver driver;

    @Given("^I navigate to TheTestRoom\\.com$")
    public void i_navigate_to_TheTestRoom_com() throws Throwable {
        System. out .println("Going to TheTestRoom.com" );
        driver = new FirefoxDriver();
        driver .navigate().to("http://www.thetestroom.com" );
    }
    @When("^I navigate to Cucumber Tutorial page$")
    public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
        System. out .println("Clicking on Cucumber Tutorial Page" );
        driver .findElement(By.linkText( "Java Cucumber Tutorial")).click();
    }
    @Then("^the page title should be visible$")
    public void the_page_title_should_be_visible() throws Throwable {
        System. out .println("Checking page title" );
        System. out .println(driver .getTitle());
        driver .quit();
    }
}

We also need to add in WebDriver (Selenium) as a dependency in our pom.xml file. Add in the dependency below:


     org.seleniumhq.selenium
     selenium-java
     2.53.0

And that’s it. Now run the Feature file on more time. Right click on it and select ‘Run As’ and then ‘Cucumber Feature’. You should now see a Firefox web browser open, navigate to TheTestRoom.com, click on the Cucumber Tutorial link and print out the title of the page.

And that’s it folks, we now have a working Eclipse Cucumber Project. In this tutorial we have learnt how to use Maven to help manage our dependencies and as well as learning how to run Cucumber Features via Eclipse. We have now covered a full tutorial on Cucumber Maven Eclipse setup.

Video Tutorial on YouTube

cucumber maven eclipse setup

Direct Video Link

Cucumber WebDriver Basic Script Tutorial

In this tutorial we will finally cover Cucumber WebDriver. We will briefly talk about WebDriver and see how we can use Cucumber and WebDriver to talk to each other. We will see how Cucumber WebDriver can work in perfect synergy.

01 Cucumber WebDriver

The first question we have to ask ourselves is ‘what is WebDriver?’. WebDriver is a browser friendly rich API application which allows us to perform user actions on a web browser. What this means is that WebDriver allows a person to write code which in turn can open a web browser, perform actions on the browser and also check to see that certain conditions were satisfied. In all, WebDriver allows a programmer to easily write tests which can be executed against an actual browser.

02 WebDriver Setup Preparation

Before we start to see how WebDriver can be used with Cucumber we need to quickly download the selenium-server-standalone jar and place it in our ‘jars’ folder, inside the ‘cucumber_project’. Navigate to http://www.seleniumhq.org/download/ and download the jar. Once you download the jar place it in the ‘jars’ directory.

Also, we will use Firefox to run our tests although you can use other browsers if you wish. Firefox can be a little easier to use and setup as there is no need to download any additional software or plugins other than having Firefox installed on your machine. At the time of writing this blog I am using Firefox version 29.0 and selenium-server-standalone version 2.53.0.

03 Step Definition for Cucumber WebDriver

Before we write any code lets quickly revisit both of the Feature File and Java Step Definition Class from the previous tutorial.

Feature File:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the WebDriver Cucumber tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to Cucumber Tutorial page
Then the page title should be visible

Step Definition Class:

package step_definition;

import cucumber.api.java.en.*;

public class myFirstStepDefinition {

        @Given( "^I navigate to TheTestRoom\\ .com$" )
        public void i_navigate_to_TheTestRoom_com() throws Throwable {
                System.out.println( "Going to TheTestRoom.com" );
        }
        @When( "^I navigate to Cucumber Tutorial page$" )
        public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
                System.out.println( "Clicking on Cucumber Tutorial Page" );
        }
        @Then( "^the page title should be visible$" )
        public void the_page_title_should_be_visible() throws Throwable {
                System.out.println( "Checking page title" );
        }
}

Here we can see that the Feature File and Step Definition Class have matching steps. All that the Step Definition class is doing is that it is printing some statements. What we would like to do is convert our Step Definition class to instead run WebDriver.

Lets try to update the first Step Definition i.e. the ‘Given’ step to simply open a Firefox browser and close it. By implementing one step at a time we are effectively breaking down a big problem into smaller easier ones. Lets first update the imports statements. Include the following statements:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

Now lets update the Given step:

@Given("^I navigate to TheTestRoom\\.com$")
public void i_navigate_to_TheTestRoom_com() throws
     System.out.println("Going to TheTestRoom.
     WebDriver driver = new FirefoxDriver();
     driver.quit();       
}

So what is happening above? Firstly we are creating a new instance of the WebDriver and calling it ‘driver’. We are then instantiating the ‘driver’ as a ‘Firefox’ browser. Since we instantiate it as a Firefox browser when we run our tests Firefox will be executed. If you wanted to use a different browser then this is where you would do it. Finally we call ‘quit’ to close the browser. Your Step Definition class should now look like this:

package step_definition;

import cucumber.api.java.en.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myFirstStepDefinition {

    @Given("^I navigate to TheTestRoom\\.com$")
    public void i_navigate_to_TheTestRoom_com() throws Throwable {
        System.out.println("Going to TheTestRoom.com");
        WebDriver driver = new FirefoxDriver();
        driver.quit();        
    }
    @When("^I navigate to Cucumber Tutorial page$")
    public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
        System.out.println("Clicking on Cucumber Tutorial Page");
    }
    @Then("^the page title should be visible$")
    public void the_page_title_should_be_visible() throws Throwable {
        System.out.println("Checking page title");
    }
}

Great, now lets try to run our new Step Definition class. So lets compile and run it:

javac -cp "jars/*;." step_definition/myFirstStepDefinition.java
java -cp "jars/*;." cucumber.api.cli.Main -p pretty -g step_definition/ features/

If everything has gone well you should now see a Firefox browser open as part of your first step, close and finally have the remaining two steps run. Congratulations as you have now just grapsed the absolute basics of running WebDriver via Cucumber. To finish off the first step we need to navigate to TheTestRoom.com. We can easily achieve this by using the ‘navigate’ method in WebDriver. Have a look below:

@Given("^I navigate to TheTestRoom\\.com$")
   public void i_navigate_to_TheTestRoom_com() throws Throwable {
   System.out.println("Going to TheTestRoom.com");
   WebDriver driver = new FirefoxDriver();
   driver.navigate().to("http://www.thetestroom.com");
}

Update your ‘Given’ step to the above and this will now navigate to TheTestRoom.com. Notice that we have removed the ‘quit’ method. This means when our test finishes the browser will still remain open but lets not worry about that now. We will discuss this ‘navigate’ method in more detail in a later blog but very briefly the ‘navigate’ method is used to tell WebDriver what URL to go to in its simplest form. With the first step now fully complete lets look at our second step definition.

04 Interacting with WebDriver

Now that we are able to open a Firefox web browser and navigate to TheTestRoom.com the next thing we should try to do (as per our Feature File scenario) is to actually go to the the Cucumber Tutorial web page. Now there are a number of different ways we can do this and the idea of interacting with web pages alone will require an entire blog post, for now lets just do something basic. If you open a web browser and navigate to TheTestRoom.com and right click on the Cucumber link and select inspect element then you should see a ‘Java Cucumber Tutorial’ inside an anchor tag.

It looks like the Cucumber Tutorial link is in fact an Anchor tag in the html. We can use this information from WebDriver to help locate the link on the page and click on it. Now as part of this Cucumber WebDriver tutorial I will be skipping a lot of important information but for now lets just try to see if its possible to find the ‘Cucumber Tutorial’ link via WebDriver and click on it. We know as a matter of fact that the text is an Anchor tag so we can use WebDriver’s anchor tag identifier to help locate the element. Once we locate it we can then click on it.

To identify the element and click on it, update your ‘When’ step to the following:

@When("^I navigate to Cucumber Tutorial page$")
   public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
   System.out.println("Clicking on Cucumber Tutorial Page");
   driver.findElement(By.linkText("Java Cucumber Tutorial")).click();
}

Notice that in this step we are just using ‘driver’ as opposed to ‘WebDriver driver’. This is to ensure that we use the same instance of the driver as from the ‘Given’ step. This means we now need to go back to your ‘Given’ step and update it to use the same instance of the ‘driver’.

WebDriver driver;
@Given("^I navigate to TheTestRoom\\.com$")
    public void i_navigate_to_TheTestRoom_com() throws Throwable {
    System.out.println("Going to TheTestRoom.com");
    driver = new FirefoxDriver();
    driver.navigate().to("http://www.thetestroom.com");
}

We have now moved the ‘driver’ outside of the ‘Given’ method as this will allow other steps to access the same instance of the ‘driver’ without having null pointers thrown around.

If we now go back to our ‘When’ step we can now see that we are trying to find an element on the web page by link and passing in the actual text of the link. Assuming we find the element we will try to perform a ‘click’ operation on it. Finally we also have to add in an import statement for the ‘By’ class. Your current version of the Step Definition class should now look like this:

package step_definition;

import cucumber.api.java.en.*;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class myFirstStepDefinition {
    WebDriver driver;

    @Given("^I navigate to TheTestRoom\\.com$")
    public void i_navigate_to_TheTestRoom_com() throws Throwable {
        System.out.println("Going to TheTestRoom.com");
        driver = new FirefoxDriver();
        driver.navigate().to("http://www.thetestroom.com");
    }
    @When("^I navigate to Cucumber Tutorial page$")
    public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
        System.out.println("Clicking on Cucumber Tutorial Page");
        driver.findElement(By.linkText("Java Cucumber Tutorial")).click();
    }
    @Then("^the page title should be visible$")
    public void the_page_title_should_be_visible() throws Throwable {
        System.out.println("Checking page title");
    }

}

To see this in action lets compile and run the code the Step Definition class as well as the Cucumber WebDriver Feature File. Assuming everything is OK you should now see a Firefox web browser open, navigate to TheTestRoom.com and then click on the Cucumber Tutorial web page. Awesome, we are almost there. Lets tackle the final step which is to check the page title.

05 Checking Page Title

The final thing to do is to check that the page title is present on the web page. Lets update our ‘Then’ step to printout the page title and then close the browser. Your ‘Then’ step should now look like this:

@Then("^the page title should be visible$")
public void the_page_title_should_be_visible() throws Throwable {
    System.out.println("Checking page title");
    System.out.println(driver.getTitle());
    driver.quit();
}

Now lets perform a final compile and run the Feature File. Your output should look like the following:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com
Going to TheTestRoom.com
Clicking on Cucumber Tutorial Page
Checking page title
Java Cucumber Tutorial - The Test Room

  Scenario: To check that the WebDriver Cucumber tutorial main page has loaded # myFirstFeature.feature:3
    Given I navigate to TheTestRoom.com                                         # myFirstStepDefinition.i_navigate_to_TheTestRoom_com()
    When I navigate to Cucumber Tutorial page                                   # myFirstStepDefinition.i_navigate_to_Cucumber_Tutorial_page()
    Then the page title should be visible                                       # myFirstStepDefinition.the_page_title_should_be_visible()

1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.113s

We should now see a Firefox web browser open, navigate to the Cucumber Tutorial web page and then print out the title of the page on the console. Congratulations as you have now just finished writing your first completed Cucumber WebDriver test.

In this tutorial we have covered the concept of using Cucumber WebDriver and seeing how we can combine the power of Feature Files with the power of WebDriver. You should now have a good understanding of how easy and simple it can be to combine Cucumber WebDriver and use their synergy to produce very Feature File based tests.

This will now set us up very nicely for all future tutorials.

Follow the Video Tutorial on YouTube:

cucumber webdriver

Direct Video Link

Cucumber Feature File Step Definition

Following on from my previous tutorial where we installed Cucumber in this tutorial we will cover the basics of Cucumber Feature File and start writing our first Step Definition class in Java.

01 Cucumber Feature File

What is a Cucumber Feature File? A Feature File in Cucumber is a simple text file that represents test scenarios. It showcases scenarios to be tested using a very structured plain text language called Gherkin. When expressing a scenario using the following keywords ‘Given’, ‘When’ and ‘Then’, these keywords can be used to very easily express some condition, an action to be take against that condition and the expected result of that action. For instance:

Given I navigate to TheTestRoom.com
When I navigate to Cucumber Tutorial page
Then the page title should be visible

Using ‘Given’, ‘When’ and ‘Then’ to express a scenario makes it very easy to understand what it is that your trying to do. This type of wording or plain text language is called Gherkin.

A basic Cucumber Feature File also consists of two other parts and these are the ‘Feature’ and ‘Scenario’ sections. The Feature section is used only for description purposes. It is used to tell the reader the types of tests that the Feature file contains. Once happy with the ‘Feature’ section of your Cucumber File we can then declare some ‘Scenario’ sections. The ‘Scenario’ sections essentially outline the actual tests. A Cucumber Feature File contains a ‘Feature’ and one or more ‘Scenario’ sections such as this:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the WebDriver Cucumber tutorial main page has loaded
Given I navigate to TheTestRoom.com
When I navigate to Cucumber Tutorial page
Then the page title should be visible

Features and scenarios make up the construct of a Cucumber Feature File.

02 Running our Cucumber Feature File

If you don’t know how to run a Feature file then read my previous tutorial first before proceeding any further.

Now lets go ahead and run our Feature File.

java -cp "jars/*" cucumber.api.cli.Main -p pretty features

When we run the above Feature file we get the following output:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

Scenario: To check that the WebDriver Cucumber tutorial main page has loaded # myFirstFeature.feature:3
Given I navigate to TheTestRoom.com
When I navigate to Cucumber Tutorial page
Then the page title should be visible

1 Scenarios (1 undefined)
3 Steps (3 undefined)
0m0.000s

You can implement missing steps with the snippets below:

@Given("^I navigate to TheTestRoom\\.com$")
public void i_navigate_to_TheTestRoom_com() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@When("^I navigate to Cucumber Tutorial page$")
public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^the page title should be visible$")
public void the_page_title_should_be_visible() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}

Lets see what is going on above. Firstly Cucumber was able to identify our Cucumber Feature File and each test step that we have written. However if you look further down it is not very happy about the steps as it says that the scenarios are ‘undefined’ as well as the test steps, what does this mean? When Cucumber says that something is undefined then this means that Cucumber was not able to find the relevant code snippets for the test steps in a Feature File. What this means is that every time Cucumber runs a Feature File it tries to look for a matching ‘Step Definition’ for a Gherking test. In this instance Cucumber is returning ‘undefined’ for all three test steps as they have not been defined anywhere. This means our next natural step is to try and write code for these test steps.

03 Writing our First Step Definition

Before writing our step definition lets take another quick look at the output from the Feature File:

.....
.....
.....
@Given("^I navigate to TheTestRoom\\.com$")
public void i_navigate_to_TheTestRoom_com() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@When("^I navigate to Cucumber Tutorial page$")
public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^the page title should be visible$")
public void the_page_title_should_be_visible() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}

Cucumber can actually be very helpful. The above code is something that Cucumber has generated for us when it tried to find a match for each test step. Each code snippet generated above is called a ‘Step Definition’. We won’t go into too much detail about step definitions now as we will continuously visit them over this entire tutorial course but for now lets copy them into a Java class and place this class in our project folder:

cd cucumber_project
mkdir step_definition
touch myFirstStepDefinition.java

Now lets VIM into the step definition class and copy in the generated step definitions as well as importing in the jars for Cucumber. Let’s also name the package to match the folder name in which the Java class is contained:

package step_definition;

import cucumber.api.java.en.*;
import cucumber.api.PendingException;

public class myFirstStepDefinition {

        @Given("^I navigate to TheTestRoom\\ .com$")
        public void i_navigate_to_TheTestRoom_com() throws Throwable {
                // Write code here that turns the phrase above into concrete actions
                throw new PendingException();
        }
        @When("^I navigate to Cucumber Tutorial page$")
        public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
                // Write code here that turns the phrase above into concrete actions
                throw new PendingException();
        }
        @Then("^the page title should be visible$")
        public void the_page_title_should_be_visible() throws Throwable {
                // Write code here that turns the phrase above into concrete actions
                throw new PendingException();
        }
}

We now need to compile the Java class:

javac "jars/*" step_definition/myFirstStepDefinition.java

Lets try to run our Feature File but also provide a ‘glue’ reference to where the ‘Step Definition’ class is:

java "jars/*;." cucumber.api.cli.Main -p pretty -g step_definition features

So what is happening? Firstly we appended the current directory to the jars with ‘.’ and then supply a reference to where the ‘Step Definition’ classes are via the ‘-g’ parameter. If done correctly then you will get an output similar to the below:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com

  Scenario: To check that the WebDriver Cucumber tutorial main page has loaded # myFirstFeature.feature:3
    Given I navigate to TheTestRoom.com                                         # myFirstStepDefinition.i_navigate_to_TheTestRoom_com()
      cucumber.api.PendingException: TODO: implement me
        at step_definition.myFirstStepDefinition.i_navigate_to_TheTestRoom_com(myFirstStepDefinition.java:11)
        at ?.Given I navigate to TheTestRoom.com(myFirstFeature.feature:4)

    When I navigate to Cucumber Tutorial page                                   # myFirstStepDefinition.i_navigate_to_Cucumber_Tutorial_page()
    Then the page title should be visible                                       # myFirstStepDefinition.the_page_title_should_be_visible()
1 Scenarios (1 pending)
3 Steps (2 skipped, 1 pending)
0m0.122s

cucumber.api.PendingException: TODO: implement me
        at step_definition.myFirstStepDefinition.i_navigate_to_TheTestRoom_com(myFirstStepDefinition.java:11)
        at ?.Given I navigate to TheTestRoom.com(myFirstFeature.feature:4)

Right, now we are getting somewhere. The output confirms that Cucumber was able to match the first test step in our Feature File to a step definition in our ‘Step Definition’ class. The glue reference in Cucumber is used to help Cucumber identify where to look for when trying to match code to test steps in Feature Files. That’s great.

When analyzing the output above we can see that 2 steps have been skipped and 1 was pending. That is because our steps in our Java code are currently throwing errors as that was what we pasted in i.e. the thrown Pending Exceptions. We now need to revisit our code and change them to do something a little more meaningful and not throw exceptions. Lets chance our code to the following:

vi step_definition/myFirstStepDefinition.java

And let’s update your Step Definition class to use print statements:

package step_definition;

import cucumber.api.java.en.*;

public class myFirstStepDefinition {

        @Given("^I navigate to TheTestRoom\\ .com$")
        public void i_navigate_to_TheTestRoom_com() throws Throwable {
                System.out.println( "Going to TheTestRoom.com" );
        }

        @When("^I navigate to Cucumber Tutorial page$")
        public void i_navigate_to_Cucumber_Tutorial_page() throws Throwable {
                System.out.println( "Clicking on Cucumber Tutorial Page" );
        }

        @Then("^the page title should be visible$")
        public void the_page_title_should_be_visible() throws Throwable {
                System.out.println( "Checking page title");
        }

}

As you can see our code is now a little more simplifier as all we are doing now is printing statements for each step definition code. Lets compile and run our Feature file:

javac -cp "jars/*" step_definition/myFirstStepDefinition.java
java -cp "jars/*;." cucumber.api.cli.Main -p pretty -g step_definition/ features/

And your output should now look like this:

Feature: To check that main tutorial course pages have loaded in TheTestRoom.com
Going to TheTestRoom.com
Clicking on Cucumber Tutorial Page
Checking page title

Scenario: To check that the WebDriver Cucumber tutorial main page has loaded # myFirstFeature.feature:3
Given I navigate to TheTestRoom.com                                         # myFirstStepDefinition.i_navigate_to_TheTestRoom_com()
When I navigate to Cucumber Tutorial page                                   # myFirstStepDefinition.i_navigate_to_Cucumber_Tutorial_page()
Then the page title should be visible                                       # myFirstStepDefinition.the_page_title_should_be_visible()

1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.113s

And thats it. You can now see that when we run our Feature file Cucumber is able to glue each test step in our Feature File to our Step Definition class and print out the statements which we supplied in our code. When each step definition code passes then Cucumber runs each step one after the other.

Now you should be much more comfortable understanding how Cucumber is able to match test steps in Feature files with code in Step Definition classes. In this tutorial we have discovered how Cucumber glues each test step to step definition code.

Video Tutorial on YouTube

cucumber feature file

Direct Video Link

Installing Cucumber Tutorial

Your a nobody if you don’t know how to run Cucumber tests and in this blog we will look at installing Cucumber. We will install Cucumber on a Windows operating system however the installation should be very similar across all operating system. To simplify this installation tutorial as much as possible we will use nothing but the command line and download a couple of Jars. This will also help us understand the process a little better whilst also keeping us away from any IDE noise.

01 – Installing Cucumber: Directory Setup

To keep this tutorial as simple as possible we will run our tests from the command line. Before doing any of this and to confirm our ‘installing Cucumber’ setup lets go ahead and setup our project directory first.

First lets create the actual directory in which all our code, jars, code etc will be saved:

mkdir cucumber_project

Now lets go into the folder and create another folder which will contain all the jars:

cd cucumber_project
mkdir jars

We now need to download all the relevant jars and place them into the jars folder. Go to http://search.maven.org/ and download the latest versions of the relevant jars (note that the URL’s below for each jar is the latest version of that jar at the point of writing this blog):

cucumber-core - http://search.maven.org/#artifactdetails|info.cukes|cucumber-core|1.2.4|jar
cucumber-java - http://search.maven.org/#artifactdetails|info.cukes|cucumber-java|1.2.4|jar
cucumber-jvm-deps - http://search.maven.org/#artifactdetails|info.cukes|cucumber-jvm-deps|1.0.5|jar
gherkin - http://search.maven.org/#artifactdetails|info.cukes|gherkin|2.12.2|bundle

With all the relevant jars downloaded we can try to run Cucumber main method and see what happens.

02 – Our First Run

Now lets see what happens when we try to run Cucumber. Firstly lets ensure we are in the correct directory i.e. in our project directory:

cd cucumber_project

And lets run the following command:

java -cp "jars/*" cucumber.api.cli.Main -p pretty .

You should see something very similar to the outcome below:

No features found at [.]

0 Scenarios
0 Steps
0m0.000s

So what is actually happening here? Firstly we are setting the jars we downloaded to the class path using -cp. Next we invoke Cucumber which tries to run our tests but in this instance there are no results for two reasons. Firstly we did not actually write any Feature files and second we told cucumber that our Feature files are in the current directory (as indicated by the ‘.’ at the end of the command). Finally we are setting the format of the returned results to be Pretty (we will discuss more on this ‘format’ point a little later in another blog. The output above confirms that Cucumber tried to run some Features files but was unable because it could not locate any Feature files to run. This is great news as we have now established a setup where Cucumber will run. This very nicely brings us to the next crucial point i.e. writing our first Feature file.

03 – Our First Feature File

It’s time to finally write our first Feature file. Lets create another directory where we can write and store our Feature files:

cd cucumber_project
mkdir features
cd features
touch myFirstFeature.feature

We have created a new directory to conveniently store our Feature files, lets write out first Feature file. Let’s use VIM to open and edit our Feature file:

vi myFirstFeature.feature

Once the file is opened we will add in the following lines:

Feature: Check TheTestRoom Home Page
Scenario: To confirm TheTestRoom loads correctly
Given I navigate to TheTestRoom
Then the website logo should be visible

cd viSo what is a Feature file and what are we trying to do. The Feature file is divided into multiple sections. The first is the ‘Feature’ section. The purpose of this section is to describe what your Feature file is trying to test. This is supposed to address a very high level test area. A Feature file should ideally contain only one ‘Feature’ section.

The second is the ‘Scenario’ section. This is used to describe the actual test case which you are trying to test. A Feature file may contain multiple Scenarios.

Lastly we have the actual test identified by the ‘Given’ and ‘Then’ keywords. This is used to describe the actual test and are known as test steps. Each test step is used to talk to the actual code. A collection of test steps is known as Gherkin language.

04 – Running our first Feature File

Now lets run the same command line again but this time with the exception being that we tell Cucumber where our Feature files are located:

java -cp "jars/*" cucumber.api.cli.Main -p pretty features

When doing so you should now see an output very similar to the below:

Feature: Check TheTestRoom Home Page

  Scenario: To confirm TheTestRoom loads correctly # myFirstFeature.feature:2
    Given I navigate to TheTestRoom
    Then the website logo should be visible

1 Scenarios (1 undefined)
2 Steps (2 undefined)
0m0.000s

You can implement missing steps with the snippets below:

@Given("^I navigate to TheTestRoom$")
public void i_navigate_to_TheTestRoom() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^the website logo should be visible$")
public void the_website_logo_should_be_visible() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

If your output is similar to the above then give yourself a pat on the back as you have now setup Cucumber to read and run Feature files. So what is happening in the output above. The output above confirms that Cucumber was able to run and identify test steps in our Feature file but failed to match up any code for each test step (more on this in a future blog). This is naturally obvious as we have not written any code to match up to any test steps in our Feature file. This however confirms our first initial setup for installing Cucumber has worked.

And that’t it. We have now proved that Cucumber in it’s simplest form is working. Installing Cucumber is as easy as that when approaching from the command line interface. Our next step will be to go ahead and write some very simple Java code and get Cucumber to ‘glue’ each test step in our Feature file to our Java class.

Video tutorial for Installing Cucumber

installing cucumber

Direct Video Link

Cucumber Page Objects Tutorial

Cucumber page objects can be used to write tests which make more sense, are easier to read and maintain over time. We can incorporate the Page Object Pattern to easily create classes which we can use to represent page objects. To learn more about Page Objects in WebDriver then click here. Page Objects are a create way of writing simple tests very quickly.

Cucumber Page Objects Video Tutorial

cucumber page objects

Direct Video Link

Page Objects when combined with Cucumber Feature files is a great way of quickly writing clean and easy to understand Feature files. We can easily express web behavior through our Gherkin files with Page Objects.

Cucumber Step Definition Class Tutorial

Cucumber step definition class in a singular instance works well but Cucumber works much better when we have multiple classes in which we can write multiple steps. When writing multiple step definition classes we can easily separate step definitions and group them into logical categories. We can easily write step definitions into groups which we can decide on how to approach. An example of this may be to group classes in objects, domains etc.

Cucumber Step Definition Class Video Tutorial

cucumber step definition

Direct Video Link

In this video tutorial we will go through setting up multiple classes to help manage us cucumber step definitions.