Passing parameters to cucumber steps

We can pass the parameters to the step methods from feature file as shown in below scenario. In below scenario, we have passed the name of website in Given step.
The main advantage of passing the parameters is that we can re-use same step method in different scenarios with different parameters.

@selenium
Feature: Simple feature

  Scenario: Test web title
    Given I am on "www.yahoo.com" page
    Then I verify that the title is "yahoo"

  Scenario: Test web title
    Given I am on "www.softpost.org" page
    Then I verify that the title is "tutorials"

Here are the step definitions for above steps. Note that both scenarios re-use same step definitions with different parameters.

package org.softpost;

import com.google.common.primitives.Bytes;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import junit.framework.Assert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class seleniumsteps {
    WebDriver driver;
    Scenario scenario;

    @Before("@selenium")
    public void launchBrowser(Scenario scenario){
        driver = new FirefoxDriver();
       this.scenario = scenario;
        System.out.println("Executing scenario " + scenario.getName());
    }

    @After("@selenium")
    public void killBrowser(){
        scenario.write("Finished scenario");
        if (scenario.isFailed()) {
            scenario.embed(((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES), "image/png");
        }
        driver.close();
        driver.quit();
    }


    @Given("^I am on \"([^\"]*)\" page$")
    public void i_am_on_page(String arg1) throws Throwable {
       driver.get("https://" + arg1);
    }

    @Then("^I verify that the title is \"([^\"]*)\"$")
    public void i_verify_that_the_title_is(String arg1) throws Throwable {
        Assert.assertTrue(driver.getTitle().toLowerCase().contains(arg1));

    }

}

You may also like...