Friday, 19 September 2014

Parameter Handling in Cucumber Java and Junit (Parameterization)

 
Parameter Handling in Cucumber Java Junit (Parameterization)

    1.       Create a new maven project.
            Refer link for reference Create a maven project in Cucumber Framework
             Create Cucumber project in maven

    2.       Add cucumber and junit dependencies in pom.xml.

                <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

3.       Create a feature file Helloworld.feature in src\test\resources. 
4.       Write the below code in Helloworld.feature

Feature: Hello World

  Scenario: Say hello
    Given I have a hello app with "Hello"
    When I ask it to say hi
    Then it should answer with "Hello"

5.       Note, the parameter here is “Hello” and is enclosed with inverted commas.6.       Now run the feature file as --> Cucumber Feature. It will give the below error. 




The step definition written has a regular expression to replace the parameter. 


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

                     package test.cucumber;

import junit.framework.Assert;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class HelloStepDefs {
       
        String greeting= "Hello";
       
        @Given("^I have a hello app with \"([^\"]*)\"$")
        public void I_have_a_hello_app_with(String greeting) throws Throwable {
                         System.out.println(" I have a app which says : "+greeting);
        }

        @When("^I ask it to say hi$")
        public void I_ask_it_to_say_hi() throws Throwable {
                        System.out.println(" I say Hi");
        }

        @Then("^it should answer with \"([^\"]*)\"$")
        public void it_should_answer_with(String arg1) throws Throwable {
                        System.out.println("It replies as : "+greeting);
        }
}



8.       Whichever method has the parameter, you can pass it to the method. 
9.       Now run the script and see the result as below.




10.       Explanation of the code : The “Hello” was a parameter in the feature file and was enclosed with inverted commas (“”). The step definition written has a regular expression to replace the parameter. When the code is run, it prints the parameter in place of the argument used in method. 

No comments:

Post a Comment