Make the most of BDD with Cucumber and LeanFT

Micro Focus Expert
Micro Focus Expert
1 1 6,154

(Technical contribution to this blog made by Ionut Stoica from the Micro Focus LeanFT R&D Team)

Behavior driven development (BDD) is an agile software development process that supports collaboration between all of the stakeholders of a product. This technique has emerged from Test Driven Development (TDD). Because of the technical nature of TDD, BDD introduced a solution to make the user stories more easily understandable by developers, QAs, business analysts and domain experts with less to no technical knowledge. To accomplish this, it was necessary to use a common, natural language. It also means replacing technical tests with scenarios or specifications that describe the behavior of the application.

There are various BDD frameworks used in agile processes: Cucumber, JBehave, Concordion, FitNesse, SpecFlow and more.  Cucumber stands out due to its growing popularity and the active community supporting it. In version 14.02, UFT Pro (LeanFT) provides native support for BDD using the Cucumber framework. This blog post briefly explains how easy it is to work with this integration in LeanFT.

 

Cucumber in more detail

Cucumber is the link between the business and technical language. With Cucumber, application features and scenarios are described using a language called Gherkin. These scenarios are written to files called feature files (files with a .feature extension).

Gherkin includes a number of keywords that are used to specify application scenarios. Scenarios specified with Gherkin can be naturally read by both business and technical stakeholders. Every line in a feature file starts with a Gherkin keyword. The following list includes the keywords found in Gherkin language:

  • Feature - The name of the specified (and tested) feature
  • Scenario - A specification of a certain application scenario, described using the Gherkin keywords. Each feature can include one or more scenarios.
  • GivenWhenThenAndBut - The Gherkin keywords that are used in the scenario specification.
  • Background - Includes a set of statements that are described using the keywords mentioned above, to be executed before every scenario in the feature
  • Scenario Outline - A parametrized scenario. Enables running the same scenario, in few iterations, each providing its own values to the scenario’s parameters.
  • Examples - A data set that is used for scenario outline.  

Each step in a feature file is automated (implemented) in files called Step Definition files.

More detailed information on the syntax can be found on the official Cucumber website at: https://cucumber.io/docs/reference

 

Creating and running Cucumber tests with LeanFT

LeanFT provides built-in integration with Cucumber and it is pretty easy to use it alongside with IntelliJ IDEA or Eclipse. The integration is based on Junit and Maven.

Before proceeding make sure your LeanFT Java SDK is installed into the Maven repository that you are using. You can follow the “Prerequisite for Maven-based project section” of our Help Center’s Create a LeanFT testing project page.

Now let’s suppose that our application is an e-commerce application that enables buying products online. A scenario for buying a product in the application might look like this: opening the browser, navigating to the application, selecting the product’s category, and then selecting the product and adding it to the cart. In the cart, the price of the product is presented.

In Gherkin, the scenario would look like this: 

Feature: Shop

  Scenario: Check speakers price
    Given I navigate to www.advantageonlineshopping.com
    When I select the speakers category
    And I add the first product to the cart
    And I navigate to the cart
    Then the total price is $269.99

 

Let’s see how this scenario can be implemented and run in a few simple steps:

 

Step 1: Open the IDE and create a new “LeanFT Cucumber Project”:

(For this blog post we will use IntelliJ IDEA)

1.png

All the necessary resources will be included in the project: the POM file for the Maven project, the Cucumber’s feature file and the step definitions file.

2.png

The main file opened in the editor will be the feature file.

The Cucumber dependencies are automatically configured in the POM file. Make sure to configure your Maven repository. Build the project to make sure all the dependencies are imported.

The project can be built from the IDE or from the command line by executing the ‘mvn clean install’ command. This command should be executed from the main directory of the project that contains the pom.xml file.

 

Step 2: Create the scenario in the feature file

In this step, create the scenarios to automate. Make sure the LeanFtFeature.feature file is opened and replace its content with the scenario provided above. 

 

Step 3: Implement the step methods in the step definitions file

The LeanFtStepDefinitions class created with the project should contain the implementation of all the steps in the feature file.

If you execute the test without implementing the steps from the feature file, then the Cucumber framework will write the missing method signatures to the output console.

Run the scenario by selecting the LeanFtTest.java file, use the mouse right click on it and select “Run LeanFtTest“.

Because the steps were not implemented, the output console will show the missing methods:

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

@When("^I select the speakers category$")
public void i_select_the_speakers_category() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I add the first product to the cart$")
public void i_add_the_first_product_to_the_cart() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

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

@Then("^the total price is \\$(\\d+)\\.(\\d+)$")
public void the_total_price_is_$(int arg1, int arg2) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

 

Now copy and paste the missing methods from the output console to the LeanFtStepDefinitions class.

The translation between the step in the feature file and the java class method is done by the regular expression provided to the annotation of the method. The regular expression can be updated to better adjust the translation between the step and the method.

Running the test again will throw the PendingException exception since the tests are not implemented yet. 

cucumber.api.PendingException: TODO: implement me
                at lft.cuke.LeanFtStepDefinitions.i_navigate_to(LeanFtStepDefinitions.java:33)
                at ✽.Given I navigate to www.advantageonlineshopping.com(LeanFtFeature.feature:4)

 

Note: Since the project is based on Maven, you might need to build it using the Maven ‘mvn clean install’ command explained above every time you change source files.

 

Step 4: Implement the methods in the step definition file using LeanFT

Now is the time for the automation itself. You should import the needed LeanFT classes and use the LeanFT SDK to automate all the methods in the step definition file. To assist you in this process, you can use any LeanFT tools, such as the Object Identification Center and Application Models.

Here is the implementation of the scenario described above (The regular expressions were slightly changed from the ones suggested by cucumber by default):

package com.company;

import static org.junit.Assert.*;
import java.io.IOException;
import com.hp.lft.report.*;
import com.hp.lft.sdk.*;
import com.hp.lft.sdk.web.*;
import com.hp.lft.verifications.Verify;
import cucumber.api.*;
import cucumber.api.java.*;
import cucumber.api.java.en.*;

public class LeanFtStepDefinitions {
    Browser browser;

    public LeanFtStepDefinitions() {}

    @Before
    public void setUp() throws GeneralLeanFtException {
        browser = BrowserFactory.launch(BrowserType.CHROME);
        browser.deleteCookies();
    }

    @After
    public void cleanUp() throws GeneralLeanFtException {
        browser.close();
    }

    //Implementation of feature’s steps
    @Given("^I navigate to www.advantageonlineshopping.com$")
    public void i_navigate_to() throws Throwable {
        browser.navigate("http://www.advantageonlineshopping.com");
    }

    @When("^I select the ([^\"]*) category")
    public void i_select_category(String categoryName) throws GeneralLeanFtException {
        String innerText = categoryName.toUpperCase() + " Shop Now ";
        Link category = browser.describe(Link.class, new LinkDescription.Builder()
                .tagName("DIV")
                .innerText(innerText).build());
        category.click();
    }

    @And("^I add the first product to the cart$")
    public void i_add_the_first_product_to_the_cart() throws GeneralLeanFtException{
        WebElement firstItem = browser.describe(Image.class, new ImageDescription.Builder()
                .className("imgProduct")
                .index(0).build());
        firstItem.click();

        Button button = browser.describe(Button.class, new ButtonDescription.Builder()
                .buttonType("submit")
                .tagName("BUTTON")
                .name("ADD TO CART").build());
        button.click();
    }

    @And("^I navigate to the cart$")
    public void i_navigate_to_the_cart() throws GeneralLeanFtException{
        WebElement cart = browser.describe(WebElement.class, new CSSDescription("svg#menuCart > path"));
        cart.click();
    }

    @Then("^the total price is (\\$[0-9,.]+)$")
    public void the_total_price_is(String price) throws GeneralLeanFtException{
        WebElement totalPrice = browser.describe(WebElement.class, new WebElementDescription.Builder()
                .className("roboto-medium ng-binding")
                .innerText(new RegExpProperty("\\$.*")).build());

        Verify.areEqual(price, totalPrice.getInnerText());
    }
}

Notes:

  • Besides the step definition methods, the class contains two methods with @Before and @After annotations. These methods are run before and after each scenario. Here we use them to launch the browser before the scenario and close it at the end.
  • To verify the result, we used the LeanFT Verify class. The verification result can be seen in LeanFT report.

 

Step 5: Run the test and see the report

After all the steps have been implemented, the test can be executed.You do not need to modify the LeanFtTest.java file.

After running the test, the LeanFT report will contain all the information about the scenarios that were run and the operations that were performed to automate every step.

The report can be opened from the “LeanFT” menu in the IDE, by selecting ‘View Last Run Results’.

3.png

 

Step 6: Adding more features, scenarios and parameters 

A feature file can contain multiple scenarios and each project can have multiple feature files.

Another very useful feature of Cucumber is the ability to parametrize scenarios. A more general scenario of what we automated would be having the category and the price provided as parameters.

For example:

Feature: Shop

  Scenario Outline: Check prices
    Given I navigate to www.advantageonlineshopping.com
    When I select the <category> category
    And I add the first product to the cart
    And I navigate to the cart
    Then the total price is <price>

    Examples:

      | category  | price   |
      | speakers  | $269.99 |
      | mice      | $9.99   |

 

The implementation for the step definition file provided above already works with this parametrized scenario, so it can be replaced in the feature file.

The entire scenario will run according to the number of rows in the “Examples” table.

All parameter names and values will be shown in LeanFT report:

 4.png

 

Step 7: Running the test using Maven

In order to run the test using the Maven command, we should mark the folder containing the LeanFtTest class as a ‘test’ folder. To do this open the pom.xml file of the project and add the testSourceDirectory entry into the <build> section.

<build>
    …
   <testSourceDirectory>src</testSourceDirectory>
    …
</build>

 

The value ‘src’ inside testSourceDirectory means that the entire src folder of the project will be treated by Maven as a folder containing tests.

To run the tests using Maven, execute the ‘mvn test’ command from the root folder of the project.

 

Summary

In this blog post we discussed the purpose and the advantages of Behavior Driven Development and how to create and run Cucumber tests using LeanFT.

Beside this out-of-the-box integration of Cucumber with LeanFT on IntelliJ IDEA and eclipse, the Cucumber framework can be used alongside LeanFT tests with other testing frameworks like TestNG or other SDKs like C# (using Specflow framework). For more information on this please check the LeanFT and Cucumber page, of the LeanFT Help Center.

 

About UFT Pro (LeanFT)

Micro Focus UFT Pro (LeanFT) is a powerful test automation solution that was built specifically for continuous testing and continuous integration. It enables advanced automation engineers and dev-testers in agile teams to leverage the standard development IDEs for test automation.

LeanFT provides a comprehensive automation SDK (available for Java, C# and JavaScript) that can be used to automate applications of all the common technologies (desktop, web and mobile). It provides plugins for Visual Studio, Eclipse, and IntelliJ, which contains powerful tools like the Object Identification Center, Application models, and much more.

You can find more information about LeanFT, in the LeanFT Help Center

Try Lean Functional Testing for yourself!

Feel free to leave a comment in the box below.

1 Comment
bharathiadidas
Frequent Visitor.

Hi ,

SAPTreeview is not working in leanFT, where i can raise the issue

The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.