Monday, 22 September 2014

Creating Datatables in Cucumber







Datatables in Cucumber


 


     1.       Create a new maven project.


    2.       Create a cucumber project in the maven setup.

     Refer link Create Cucumber Project


    3.       Now Create a feature file Calculator.feature in src\test\resources.

    4.       Write the below code in Calculator.feature

Feature: Cucumber can convert Gherkin data tables to a list of a type you specify.

  Scenario: The sum of a list of numbers should be calculated
    Given a list of numbers
      | 1   |
      | 4   |
      | 1 |
    When I summarize them
    Then should I get 6

    5.       Note the list of numbers in this example is given in the form of a list.

    6.       Now run the feature file as à Cucumber Feature. It will give the below error.

 
    7.       Now copy the snippet steps and create  a step definition file with the below code.   

    8.       Name the step definition file as Calculatorsteps.java

   package test.cucumber;
  import cucumber.api.java.en.Given;
      import cucumber.api.java.en.Then;
      import cucumber.api.java.en.When;

      import java.util.List;

      import static org.hamcrest.CoreMatchers.is;
      import static org.junit.Assert.assertThat;



   public class calculatorsteps {
     

          private List<Integer> numbers;
          private int sum;

         @Given("^a list of numbers$")
          public void a_list_of_numbers(List<Integer> numbers) throws Throwable {
              this.numbers = numbers;
          }

          @When("^I summarize them$")
          public void i_summarize_them() throws Throwable {
              for (Integer number : numbers) {
                  sum += number;
              }
          }

          @Then("^should I get (\\d+)$")
          public void should_I_get(int expectedSum) throws Throwable {
              assertThat(sum, is(expectedSum));
          }
      }


   9.       In this example, create a list and assign the numbers in datatable to the list and perform addition of the numbers in the list and compare the result.
  
   10.       Now run the script and see the result as below.

 



    11.       Explanation of code : In this example, we have data in gherkin language written separated using “|” . For the implementation in step definition, we have created a list in the code and assigned the numbers in datatable to the list and perform addition of the numbers in the list and compare the result.

    12.       Conclusion : Cucumber supports in built data tables which can be used to define normal scenarios in gherkin language.
 


 



 


 
 

No comments:

Post a Comment