Thursday, August 2, 2018

Parameterization in Cucumber - Bean Objects

Another way to pass data table is through data table transformer to convert the data table to a list of bean object. You don't need to define data entry transformer in the previous version of Cucumber 3.0. But you have to do that if you use the latest version of Cucumber.

Here is the feature definition.

  Scenario: Login Failure
    Given User is on Home Page
    And Sign In link is displayed
    When User clicks the Sign In link
    And User enters Credentials to login
    | Username | Password|
    | username | password|
    | username1 | password1|
    Then User should be login failed message

And Bean definition.

package me.simplejavautomation.data;

public class Credentials {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}


Define and register table transformer.

package me.simplejavautomation.data.transformer;

import java.util.Locale;
import java.util.Map;

import cucumber.api.TypeRegistry;
import cucumber.api.TypeRegistryConfigurer;
import io.cucumber.datatable.DataTableType;
import io.cucumber.datatable.TableEntryTransformer;
import me.simplejavautomation.data.Credentials;

public class TypeRegistryConfiguration implements TypeRegistryConfigurer {

    @Override
    public Locale locale() {
        return Locale.ENGLISH;
    }

    @Override
    public void configureTypeRegistry(TypeRegistry typeRegistry) {
        typeRegistry.defineDataTableType(new DataTableType(Credentials.class,
                  new TableEntryTransformer<Credentials>() {

            @Override
            public Credentials transform(Map<String, String> entry)
                   throws Throwable {
                Credentials credentials = new Credentials();
                credentials.setUsername(entry.get("Username"));
                credentials.setPassword(entry.get("Password"));
                return credentials;
            }
        }));
    }
}


Add transformer package to CucumberOptions configuration

package me.simplejavautomation;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/features",
       glue = { "me.simplejavautomation.stepdefs",
        "me.simplejavautomation.data.transformer" })
public class CucumberTestRunner {

}

And then you are ready to go.

No comments:

Post a Comment