Cucumber examples table

Cucumber examples table DEFAULT

Cucumber - Data Tables



While working on automation, we may face variety of scenarios. Each scenario carries a different meaning and needs.

Since the beginning, we have been taking an example of login functionality for a social networking site, where we just had two input parameters to be passed. Let’s think of some more possibility. How about “New user registration” functionality? Typically, what can be the input parameters while registering a new user for a social networking site? Something like the following −

  • User Name
  • Email Address
  • Password
  • Re-enter password
  • Birthdate
  • Gender
  • Phone number

Feature − New user registration.

Verify that the new user registration is unsuccessful after passing the incorrect inputs.

Given I am on a new user registration page.

When I enter the user name and an e-mail address as email address and password as, and re-enter password as and Birthdate as and Gender as and phone number as then the user registration should be unsuccessful.

It looks a bit messy at first glance. So, is there any better way to manage such chunk of inputs? Answer can be “Data Table”. Data table is a set of input to be provided for a single tag. This tag can be GIVEN, WHEN, or THEN.

Let’s write the above scenario with the help of data table and it will look like the following −

Given I am on a new user registration page

When I enter valid data on the page

| Fields | Values | | First Name | Tom | | Last Name | Kenny | | Email Address | [email protected] | | Re-enter Email Address | [email protected] | | Password | Password1 | | Birthdate | 01 |

Then the user registration should be successful.

Example

Let’s automate an example of a data table.

Step 1 − Create a Maven Test Project named “DataTableTest”.

  • Go to File → New → Others → Maven → Maven Project → Next.

  • Provide group Id (group Id will identify your project uniquely across all projects).

  • Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name which is in lowercase).

  • Click on Finish.

  • Open pom.xml −

    • Go to package explorer on the left hand side of Eclipse.

    • Expand the project CucumberTest.

    • Locate pom.xml file.

    • Right-click and select the option, Open with “Text Editor”.

  • Add dependency for Selenium: This will indicate Maven, which Selenium jar files are to be downloaded from the central repository to the local repository.

    • Open pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag.

    • Inside the dependencies tag, create dependency tag. (<dependency></dependency>).

    • Provide the following information within the dependency tag.

<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.47.1</version> </dependency>
  • Add dependency for Cucumber-Java − This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository.

    • Create one more dependency tag.

    • Provide the following information within the dependency tag.

<dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.0.2</version> <scope>test</scope> </dependency>
  • Add dependency for Cucumber-JUnit − This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository.

    • Create one more dependency tag.

    • Provide the following information within the dependency tag.

<dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.0.2</version> <scope>test</scope> </dependency>
  • Add dependency for JUnit − This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository.

    • Create one more dependency tag.

    • Provide the following information within the dependency tag

<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
  • Verify binaries.

    • Once pom.xml is edited successfully, save it.

    • Go to Project → Clean − It will take a few minutes.

Step 2 − Create a package named dataTable under src/test/java

Step 3 − Create a Feature file.

  • Create a feature file, named as dataTable.feature inside the package dataTable (see section scenario outline for more detailed steps).

  • Write the following text.

    Feature − Data table

    Verify that the new user registration is unsuccessful after passing incorrect inputs.

    Scenario:

    Given I am on the new user registration page

    When I enter invalid data on the page

| Fields | Values | | First Name | Tom | | Last Name | Kenny | | Email Address | [email protected] | | Re-enter Email Address | [email protected] | | Password | Password1 | | Birthdate | 01 |

Then the user registration should be unsuccessful

Step 4 − Create step definition file.

  • Create the step definition file named as ‘dataTable.java’ inside the package dataTable (see section scenario outline for more detailed steps).

  • Write the following code.

package dataTable; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; import cucumber.table.DataTable; public class stepdefinition { WebDriver driver = null; @Given("^I am on new user registration page$") public void goToFacebook() { //Intiate web browser instance. driver = new FirefoxDriver(); driver.navigate().to("https://www.facebook.com/"); } @When("^I enter invalid data on the page$") public void enterData(DataTable table){ //Initialize data table List<list> data = table.raw(); System.out.println(data.get(1).get(1)); //Enter data driver.findElement(By.name("firstname")).sendKeys(data.get(1).get(1)); driver.findElement(By.name("lastname")).sendKeys(data.get(2).get(1)); driver.findElement(By.name("reg_email__")).sendKeys(data.get(3).get(1)); driver.findElement(By.name("reg_email_confirmation__")). sendKeys(data.get(4).get(1)); driver.findElement(By.name("reg_passwd__")).sendKeys(data.get(5).get(1)); Select dropdownB = new Select(driver.findElement(By.name("birthday_day"))); dropdownB.selectByValue("15"); Select dropdownM = new Select(driver.findElement(By.name("birthday_month"))); dropdownM.selectByValue("6"); Select dropdownY = new Select(driver.findElement(By.name("birthday_year"))); dropdownY.selectByValue("1990"); driver.findElement(By.className("_58mt")).click(); // Click submit button driver.findElement(By.name("websubmit")).click(); } @Then("^User registration should be unsuccessful$") public void User_registration_should_be_unsuccessful() { if(driver.getCurrentUrl().equalsIgnoreCase("https://www.facebook.com/")){ System.out.println("Test Pass"); } else { System.out.println("Test Failed"); } driver.close(); } }

Step 5 − Create a runner class file.

  • Create runner class named as runTest.java inside the package.

  • Write the following code.

package dataTable; import org.junit.runner.RunWith; import cucumber.junit.Cucumber; @RunWith(Cucumber.class) @Cucumber.Options(format = {"pretty", "html:target/cucumber"}) public class runTest { }
  • Save the file.

  • Run the test using the option

    • Select runTest.java file from the package explorer.

    • Right-click and select the option, Run as.

    • Select JUnit test.

You may observe the following things upon successful execution.

  • Facebook website gets loaded.

  • Data will be entered on the registration page.

  • Submit button will be clicked.

  • We will see that home page will not displayed and “Test Pass” will be written on the console.

Sours: https://www.tutorialspoint.com/cucumber/cucumber_data_tables.htm

Data Tables in Cucumber

Data Tables in Cucumber are quite interesting and can be used in many ways. DataTables are also used to handle large amounts of data. They are quite powerful but not the most intuitive as you either need to deal with a list of maps or a map of lists. Most of the people get confused with Data tables & Scenario outline, but these two works completely differently.

Difference between Scenario Outline & Data Table

Scenario Outline:

  • This uses Example keyword to define the test data for the Scenario
  • This works for the whole test
  • Cucumber automatically run the complete test the number of times equal to the number of data in the Test Set

Test Data:

  • No keyword is used to define the test data
  • This works only for the single step, below which it is defined
  • A separate code needs to understand the test data and then it can be run single or multiple times but again just for the single step, not for the complete test

As I said above, the Data Tables can be used in many ways because it has provided many different methods to use. Let's just go through a few most popular methods. I will choose a simple scenario to illustrate the working of the Data Table but we will make effective use of this when we will do Cucumber Framework in the next series of this Cucumber Tutorial.

Data Tables in Cucumber

In this example, we will pass the test data using the data table and handle it using Raw() method.

The complete scenario is same as what we have done earlier. But the only difference is in this, we are not passing parameters in the step line and even we are not using Examples test data. We declared the data under the step only. So we are using Tables as arguments to Steps.

If you run the above scenario without implementing the step, you would get the following error in the Eclipse console window.

DataTable_Cucumber_1

Copy the above hint in the Step Definition file and complete the implementation.

The implementation of the above step will be like this:

The complete test Implementation

Test Runner Class

Feature File

Step Definition

Project Explorer

DataTable_Cucumber_1

Run the test by Right Click on TestRunner class and Click Run As  > JUnit Test Application. you will notice that Cucumber will automatically figure out, what to provide in the Username and Password field.

In the next chapter of Data Tables in Cucumber using Maps, we will handle little complex data.

Sours: https://www.toolsqa.com/cucumber/data-tables-in-cucumber/
  1. Pioneer auto sales
  2. Garden grove masjid address
  3. Tank fish discord

Using data tables in Cucumber-JVM for better readable specifications

If you have ever worked in a team that practiced BDD and used Cucumber or SpecFlow to create executable specifications, you’ll know that writing scenarios that are readable is hard. As in: really, really hard.

In this blog post, I want to take a closer look at a feature of the Java Cucumber bindings that can help you write specs that are easy on the eye, and that I feel isn’t talked about often enough: using data tables.

Data tables are tables that you can pass as an argument to an individual step. The data in this data table can then be processed in the underlying step definition. As such, data tables should not be confused with example tables, which are tables containing examples for entire scenarios, to be used with scenario outlines. Data tables, on the other hand, allow you to use more complex data structures as an argument to an individual step.

Let’s take a look at a couple of examples of the use of different forms of data tables, and how they compare to specifying the same data in more verbose textual format.

Example 1 - Key-value pairs

As a first example, let’s consider the situation where you’ll need to specify some sort of initial state that consists of multiple objects (‘things’) that can be modeled as a simple key-value pair. Some examples could be:

  • currencies and their associated currency code (USD, EUR, etc.)
  • airports and their IATA location identifier (LAX, JFK, etc.)
  • employee names and their associated employee number

or, in the example below, football clubs and the stadium they play their home games at. Often, I see teams model these in their specifications like this:

and the step definition associated with these steps:

While this works, technically, I believe there are two inherent problems with this example. First, it is tedious to read because of the repeated text. Second, we’re using three steps (a and two s) to specify a single initial state, which to me feels counterintuitive. As a whole, this kind of specification reminds me a little too much of this iconic movie scene..

There’s a much better way to include the same data in your specification, and that is by using a data table. The same specification can be rewritten as

Please note that the first row does contain data, not table headers, even though the syntax highlighting suggests otherwise!

and the associated step definition might look like this:

As you can see, Cucumber is able to automatically convert the data table that is passed as an argument to the step to a , which is essentially a collection of key-value pairs. You can then iterate over the key-value pairs in the using a construct and process each entry as required for your acceptance test.

Running this example yields the following output:

Example 2 - Multi-column tables

What about the situations where you want to model data entities that have more attributes, and therefore cannot be simply represented as a key-value pair? Think of entities such as:

  • Addresses (a combination of a street name, a house number, a zip code, a city, …)
  • Flight information (a combination of a flight number, an airline, an airport of origin, a destination airport, …)
  • Bank transfers (a combination of a date, an amount, a source bank account, a destination bank account, …)

or, in this example, data related to specific players of a football club. We could choose to specify this data as:

and implements these steps using a step definition method such as

This example, too, suffers from the same problems as the previous one. There’s a lot of repetition, which makes the specification boring to read, and we need multiple steps to create an initial state. Let’s do better!

The same state can be modeled with a data table that might look like this:

Note that I decided to include table headers here, as this makes it much clearer which column corresponds to which attribute for a player. Using table headers is also really helpful in the associated step definition code, as we can see in this example implementing the step:

Cucumber automatically converts the table structure we’ve seen in this example to an argument of type , or, in plain English, a of s, where each represents a data entity (a football player, here), and each player has specific attributes, represented by the keys and their values in each .

To iterate over the , we can use a loop again, as can be seen in the code snippet above. Each property value is retrieved using its corresponding key, which is equal to the header of the respective data table column in our specification.

Running this example yields the following output:

Example 3 - Tables with both row and column headers

As a final example, let’s look at an even more intricate data structure: a table with both column and row headers. Example usages of such a table can be:

  • Specifying availability per weekday and time of day for a delivery service
  • Specifying train fare rates for combinations of seating class and age group for a railway company
  • Specifying the distribution of gold, silver and bronze medals for a number of countries competing in the Olympics

or, in the example below, final scores for football matches. One way I’ve seen teams specify data similar to this:

implemented by

Once again, a lot of repetition in the specs, which makes them boring to read, you know the drill by now. Fortunately, there’s a way out of this mess, too:

Here, too, the syntax highlighting may be a little confusing: the first column in this table contains row headers.

As you can see, the aforementioned state can be modeled using a table with both row and column headers. Here, too, Cucumber is able to directly transform this into a suitable data structure:

The data we specified is transformed into a , where the keys are the row headers (the dates on which the matches were played), and the values were s, too, with keys corresponding to the column headers (club names) and values containing the number of goals scored by each team.

In this example, too, we iterate over the outer to process each individual match using , and we use the column headers to get the values (the scores for each team) we want from the inner using .

Running this example yields the following output:

In this article, we’ve seen some examples of how to use data tables to specify complex data more efficiently in Cucumber .feature files, how Cucumber automatically transforms these tables into specific data structures, and how we can iterate over and process that data effectively.

Effectively, what we’ve done is removing the iterative nature from our specifications to make them more readable, and move the iterating over the data to our step definitions. In a follow-up article, I’ll dive deeper into using data table transformers to handle complex data structures in an even more efficient way.

All the code shown in this blog post can be found on GitHub.

"
Sours: https://www.ontestautomation.com/using-data-tables-in-cucumber-jvm-for-better-readable-specifications/
#12 - Scenario Outline with Examples keyword in #Cucumber (Data Driven Testing) - Latest Features

Keywords

Gherkin uses a set of special keywords to give structure and meaning to executable specifications. Each keyword is translated to many spoken languages; in this reference we’ll use English.

Most lines in a Gherkin document start with one of the keywords.

Comments are only permitted at the start of a new line, anywhere in the feature file. They begin with zero or more spaces, followed by a hash sign () and some text.

Block comments are currently not supported by Gherkin.

Either spaces or tabs may be used for indentation. The recommended indentation level is two spaces. Here is an example:

The trailing portion (after the keyword) of each step is matched to a code block, called a step definition.

Each line that isn’t a blank line has to start with a Gherkin keyword, followed by any text you like. The only exceptions are the feature and scenario descriptions.

The primary keywords are:

There are a few secondary keywords as well:

  • (Doc Strings)
  • (Data Tables)
  • (Tags)
  • (Comments)

Gherkin is localised for many spoken languages; each has their own localised equivalent of these keywords.

Feature

The purpose of the keyword is to provide a high-level description of a software feature, and to group related scenarios.

The first primary keyword in a Gherkin document must always be , followed by a and a short text that describes the feature.

You can add free-form text underneath to add more description.

These description lines are ignored by Cucumber at runtime, but are available for reporting (they are included by reporting tools like the official HTML formatter).

The name and the optional description have no special meaning to Cucumber. Their purpose is to provide a place for you to document important aspects of the feature, such as a brief explanation and a list of business rules (general acceptance criteria).

The free format description for ends when you start a line with the keyword , , or (or their alias keywords).

You can place tags above to group related features, independent of your file and directory structure.

Descriptions

Free-form descriptions (as described above for ) can also be placed underneath /, , and .

You can write anything you like, as long as no line starts with a keyword.

Descriptions can be in the form of Markdown - formatters including the official HTML formatter support this.

Rule

The (optional) keyword has been part of Gherkin since v6.

The keyword is still pretty new. It has been ported in a lot of Cucumber implementation already. Yet if you encounter issues, check the documentation of your Cucumber implementation to make sure it supports it.

The purpose of the keyword is to represent one business rule that should be implemented. It provides additional information for a feature. A is used to group together several scenarios that belong to this business rule. A should contain one or more scenarios that illustrate the particular rule.

For example:

Example

This is a concrete example that illustrates a business rule. It consists of a list of steps.

The keyword is a synonym of the keyword .

You can have as many steps as you like, but we recommend 3-5 steps per example. Having too many steps will cause the example to lose its expressive power as a specification and documentation.

In addition to being a specification and documentation, an example is also a test. As a whole, your examples are an executable specification of the system.

Examples follow this same pattern:

  • Describe an initial context ( steps)
  • Describe an event ( steps)
  • Describe an expected outcome ( steps)

Steps

Each step starts with , , , , or .

Cucumber executes each step in a scenario one at a time, in the sequence you’ve written them in. When Cucumber tries to execute a step, it looks for a matching step definition to execute.

Keywords are not taken into account when looking for a step definition. This means you cannot have a , , , or step with the same text as another step.

Cucumber considers the following steps duplicates:

This might seem like a limitation, but it forces you to come up with a less ambiguous, more clear domain language:

Given

steps are used to describe the initial context of the system - the scene of the scenario. It is typically something that happened in the past.

When Cucumber executes a step, it will configure the system to be in a well-defined state, such as creating and configuring objects or adding data to a test database.

The purpose of steps is to put the system in a known state before the user (or external system) starts interacting with the system (in the steps). Avoid talking about user interaction in ’s. If you were creating use cases, ’s would be your preconditions.

It’s okay to have several steps (use or for number 2 and upwards to make it more readable).

Examples:

  • Mickey and Minnie have started a game
  • I am logged in
  • Joe has a balance of £42

When

steps are used to describe an event, or an action. This can be a person interacting with the system, or it can be an event triggered by another system.

It’s strongly recommended you only have a single step per Scenario. If you feel compelled to add more, it’s usually a sign that you should split the scenario up into multiple scenarios.

Examples:

  • Guess a word
  • Invite a friend
  • Withdraw money

Most software does something people could do manually (just not as efficiently).

Try hard to come up with examples that don’t make any assumptions about technology or user interface. Imagine it’s 1922, when there were no computers.

Implementation details should be hidden in the step definitions.

Then

steps are used to describe an expected outcome, or result.

The step definition of a step should use an assertion to compare the actual outcome (what the system actually does) to the expected outcome (what the step says the system is supposed to do).

An outcome should be on an observable output. That is, something that comes out of the system (report, user interface, message), and not a behaviour deeply buried inside the system (like a record in a database).

Examples:

  • See that the guessed word was wrong
  • Receive an invitation
  • Card should be swallowed

While it might be tempting to implement steps to look in the database - resist that temptation!

You should only verify an outcome that is observable for the user (or external system), and changes to a database are usually not.

And, But

If you have successive ’s, ’s, or ’s, you could write:

Or, you could make the example more fluidly structured by replacing the successive ’s, ’s, or ’s with ’s and ’s:

*

Gherkin also supports using an asterisk () in place of any of the normal step keywords. This can be helpful when you have some steps that are effectively a list of things, so you can express it more like bullet points where otherwise the natural language of etc might not read so elegantly.

For example:

Could be expressed as:

Background

Occasionally you’ll find yourself repeating the same steps in all of the scenarios in a .

Since it is repeated in every scenario, this is an indication that those steps are not essential to describe the scenarios; they are incidental details. You can literally move such steps to the background, by grouping them under a section.

A allows you to add some context to the scenarios that follow it. It can contain one or more steps, which are run before each scenario, but after any Before hooks.

A is placed before the first /, at the same level of indentation.

For example:

is also supported at the level, for example:

You can only have one set of steps per or . If you need different steps for different scenarios, consider breaking up your set of scenarios into more s or more s.

For a less explicit alternative to , check out conditional hooks.

Tips for using Background

  • Don’t use to set up complicated states, unless that state is actually something the client needs to know.
    • For example, if the user and site names don’t matter to the client, use a higher-level step such as .
  • Keep your section short.
    • The client needs to actually remember this stuff when reading the scenarios. If the is more than 4 lines long, consider moving some of the irrelevant details into higher-level steps.
  • Make your section vivid.
    • Use colourful names, and try to tell a story. The human brain keeps track of stories much better than it keeps track of names like , , , and so on.
  • Keep your scenarios short, and don’t have too many.
    • If the section has scrolled off the screen, the reader no longer has a full overview of what’s happening. Think about using higher-level steps, or splitting the file.

Scenario Outline

The keyword can be used to run the same multiple times, with different combinations of values.

The keyword is a synonym of the keyword .

Copying and pasting scenarios to use different values quickly becomes tedious and repetitive:

We can collapse these two similar scenarios into a .

Scenario outlines allow us to more concisely express these scenarios through the use of a template with -delimited parameters:

Examples

A must contain one or more (or ) section(s). Its steps are interpreted as a template which is never directly run. Instead, the is run once for each row in the section beneath it (not counting the first header row).

The steps can use delimited parameters that reference headers in the examples table. Cucumber will replace these parameters with values from the table before it tries to match the step against a step definition.

You can also use parameters in multiline step arguments.

In some cases you might want to pass more data to a step than fits on a single line. For this purpose Gherkin has and .

Doc Strings

are handy for passing a larger piece of text to a step definition.

The text should be offset by delimiters consisting of three double-quote marks on lines of their own:

In your step definition, there’s no need to find this text and match it in your pattern. It will automatically be passed as the last argument in the step definition.

Indentation of the opening is unimportant, although common practice is two spaces in from the enclosing step. The indentation inside the triple quotes, however, is significant. Each line of the Doc String will be dedented according to the opening . Indentation beyond the column of the opening will therefore be preserved.

Doc strings also support using three backticks as the delimiter:

This might be familiar for those used to writing with Markdown.

Whilst all current versions of Cucumber support backticks as the delimiter, many tools like text editors don’t (yet).

Data Tables

are handy for passing a list of values to a step definition:

Just like , will be passed to the step definition as the last argument.

Table Cell Escaping

If you want to use a newline character in a table cell, you can write this as . If you need a as part of the cell, you can escape it as . And finally, if you need a , you can escape that with .

Data Table API

Cucumber provides a rich API for manipulating tables from within step definitions. See the Data Table API reference reference for more details.

The language you choose for Gherkin should be the same language your users and domain experts use when they talk about the domain. Translating between two languages should be avoided.

This is why Gherkin has been translated to over 70 languages .

Here is a Gherkin scenario written in Norwegian:

A header on the first line of a feature file tells Cucumber what spoken language to use - for example for French. If you omit this header, Cucumber will default to English ().

Some Cucumber implementations also let you set the default language in the configuration, so you don’t need to place the header in every file.

Sours: https://cucumber.io/docs/gherkin/reference/

Table cucumber examples

Cucumber Data Tables Example in Java

In our previous post, we learned how to create scenario outline that can be used to repeat the same steps with different parameters. In this tutorial, we will show you some Cucumber Data Tables Example in Java and how it differs in Scenario Outline and how you can implement it in your Test Cases.

Cucumber Data Tables can be used to add multiple parameters in a Step Definition in a tabular form rather than putting all the parameters in the Gherkin statement. This is much easier to read and multiple rows of data can be passed in the same step. Let’s take some Cucumber Data Tables Example:

Cucumber Data Tables Example in Java

Data Table without Header Example

Here’s an example on how to implement Data Tables without a Header. For example, we want to test the registration form the user is submitting in our application. We can either put all the arguments inside the Gherkin statement or use a table to list all the arguments like we used below:

Scenario: Valid Registration Form Information Given User submits a valid registration form | John | Doe | jdoe | testPass1 | [email protected] | Then System proceeds with registration

Notice that we used pipe delimiter (|) to create a table form. Below is the Step Definition we defined:

private boolean isValid; @Given("User submits a valid registration form") public void userSubmitsAValidRegistrationForm(DataTable dataTable) { List<String> signUpForm = dataTable.asList(); String fName = signUpForm.get(0); String lName = signUpForm.get(1); String username = signUpForm.get(2); String password = signUpForm.get(3); String email = signUpForm.get(4); isValid = isValid(fName, lName, username, password, email); } private boolean isValid(String fName, String lName, String username, String password, String email) { if (StringUtils.isAnyBlank(fName, lName, username, password, email) || !EmailValidator.getInstance().isValid(email)) { return false; } return true; }

From the code above, we add the DataTable parameter in our method declaration. This object contains our arguments that we can retrieved to use in our logic. Since we don’t have a header, we can just get the List object and get the values starting from 0 index.

Data Table with Header and Single Row Example

Below is a cucumber data tables example with header. Adding a header in your table makes it easier to read and maintain.

Scenario: Valid Registration Form Information with Header Given User submits a valid registration form header | FirstName | LastName | Username | Password | Email | | John | Doe | jdoe | testPass1 | [email protected] | Then System proceeds with registration

And in our Java code, we can then just get the Map object that contains the Key/Value pairs of our arguments. For example, we can retrieve the First Name by using map.get(“FirstName”).

@Given("User submits a valid registration form header") public void userSubmitsAValidRegistrationFormHeader(DataTable dataTable) { List<Map<String, String>> signUpForms = dataTable.asMaps(String.class, String.class); String fName = signUpForms.get(0).get("FirstName"); String lName = signUpForms.get(0).get("LastName"); String username = signUpForms.get(0).get("Username"); String password = signUpForms.get(0).get("Password"); String email = signUpForms.get(0).get("Email"); isValid = isValid(fName, lName, username, password, email); }

Since we only have 1 row in our Gherkin, we can then just use List.get(0) to retrieve the first row. Then get the argument by using map.get(“HeaderName”).

Data Table with Header and Multiple Rows Example

Finally, we will show you an example that contains multiple rows of data. This is helpful when you want to test multiple combination of data in a step. Here’s an example of our Gherkin:

Scenario: Valid Registration Form Information with Header and Multiple Rows Given User submits valid registration forms | FirstName | LastName | Username | Password | Email | | John | Doe | jdoe | testPass1 | [email protected] | | Anne | Smith | asmith | testPass2 | [email protected] | | Mike | Stewart | mstewart | testPass3 | [email protected] | Then All Forms will proceed with registration

And here’s our Step Definition. Notice that in our previous example, we only retrieve the first row by using get(0) method of List. Now, we will loop all the values in the List. Our List object contains the Map object which represents a Row in a table. So in our example, we have 3 rows of data which means that our List object holds 3 objects of Map. The Map object contains the columns of our data. Our example have 5 columns which then translates that our Map object will have 5 key/value pairs inside.

@Given("User submits valid registration forms") public void userSubmitsValidRegistrationForms(DataTable dataTable) { List<Map<String, String>> signForms = dataTable.asMaps(); formValidationResults = new ArrayList<Boolean>(); for (Map<String, String> form : signForms) { String fName = form.get("FirstName"); String lName = form.get("LastName"); String username = form.get("Username"); String password = form.get("Password"); String email = form.get("Email"); boolean validationResult = isValid(fName, lName, username, password, email); formValidationResults.add(validationResult); } }

And that’s it. Next tutorial is about how you can run your feature files automatically when building a maven project. Let us know in the comments if you have questions.

Share this tutorial!

Sours: https://javapointers.com/automation/cucumber/cucumber-data-tables-example-in-java/
How To pass Datatables in Cucumber Automation Testing - Cucumber Java Tutorial - StudySimple -

Different methods to implement Cucumber Data tables in Java

There are different ways to handle data tables in Cucumber scenarios. Which method of data table you use depends on your project and complexity of your test. In this article I will show some methods with their examples. I will also discuss the advantages and disadvantages of each method. In the end, it is up to you to decide which method best suits your needs.

Method 1: List

You can add data to your Gherkin as a list. This method is best used when you have a small data set of the same data type and the order of the data is unlikely to change or not important (for example: a list of numbers that you want to loop through).
For example:

In your step file, this data can be read as:

This is probably the simplest method to implement data tables. In this case we have 3 string values. Instead of strings you can switch the data type of the list to any data type that you want. However, the disadvantage of this method is that you can only use a single data type, so only strings or only integers, etc. You cannot mix the different data types into the same list. Furthermore, you are dependent on the order of your data in your list. If you want to add an item to a position other then the end of the list, you will need to update your indexes of the rest if each data point has its own function.

Summary:
+ Simple to implement
- Limited to single data type in list
- You have to keep track of the order of your data in the list

Method 2: Map

Instead of a list, we can also use a map. This solves the problem of keeping track of the order of the data in your list. This method is best used when you have a small/medium data set of the same data type and each data value has its own function.
In Gherkin this would look like:

In your step file, this data can be read as:

Because we are now using a map, the order of the data is no longer an issue. We can access the data by simply calling the key which is the first column of the data. However, we can still only have the same data type in the entire map. In this case . Keep in mind that keys in the map need to be unique.

Summary:
+ Fairly simple to implement
+ The order of your data is not an issue
- Limited to single data type in map

Method 3: Custom object

You can also create a custom object for your data table. A great advantage of using this method is that you can handle different data types in your data table. For example: if we want to create data for a product in a store we can create an object called Product.

In Gherkin we can give values to each field of the object:

It is important that the names in the top row are an exact match with your field names of your custom object. Cucumber is only forgiving in capitalization of the first letter. Also note that the topmost row now has the "keys" and the second row contains the data where in method 2 the first column was the key and the second column the value.

In your step file, this data can be read as follows:

In order to access the fields we need to add getters to the class. So the final Java file looks like:

With the getters in place, we can now access the fields in our steps. For example:

As you can see we can now use multiple data types in our data input (strings, integers and doubles in our case). Another advantage is that you can work with multiple data objects like this:

And access them all in the steps file with for example a loop:

Summary:
+ Multiple data types possible
+ The order of your data is not an issue
+ Multiple data objects in a single step
- Bit more complex to implement

Method 4: Custom objects with fake data

This is a more complex usage of data tables where I no longer wanted to create new test data every time I ran my test. It is actually an extension of method 3. This method is highly recommended when working in a test environment where your test data has to be unique each time you run your test (for example when filling in forms) or when working with large data sets. It allows you to control the values that you want and randomize other values.

Like we did in method 3, we need to create an object. But we now add a Constructor which generates our fake data. I use the Java Faker package to generate the fake data. For example:

In Gherkin we give values only to the fields that we want to control the values of:

And then in our steps file, we generate the rest of the data:

As you can see I am calling the Java method in ContactFormData. You can add this method to the class with the following code:

This Java method calls the generic Java method in my class (which we have not yet created). In calling this method it passes on the initialData that I filled in in my Gherkin and it passes on a new data object using the constructor that generates the fake data. So all we need now is the generic method somewhere (In my case it is located in a class called DataHelper. You can place this method anywhere you want). This generic method only needs to be defined once for your entire project since it works with generic class types.

This method for data tables in Cucumber is also very handy when you have large data sets. Since you only fill in some fields in your Gherkin and generate data for the rest of the fields, your feature file is not cluttered with unnecessary information.

Summary:
+ Possibility to generate fake data
+ Multiple data types possible
+ The order of your data is not an issue
+ Multiple data objects in a single step
- Complexity of code

Sours: https://academy.capgemini.nl/blog/different-methods-implement-cucumber-data-tables-java

You will also be interested:

.



1127 1128 1129 1130 1131