07
Jan

Custom data types with Cucumber steps and datatables

Cucumber custom types configuration
=====================================

The type registry is used to configure 
	parameter types and 
	data table types in cucumber feature files. 

In order to configure your own custom types, following steps can be defined:

Step 1: Create your custom implementation for TypeRegistryConfigurer anywhere on the glue path. 
=================================================================================================

import java.util.Locale;

public class TypeRegistryConfiguration implements TypeRegistryConfigurer {

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

	@Override
	public void configureTypeRegistry(TypeRegistry typeRegistry) {
		typeRegistry.defineParameterType(new ParameterType<>(
				"account_type", 	// name
				"savings|checking", // regexp
				AccountType.class, 	// type
				AccountType::new 	// transformer function
		));
	}

	static class AccountType {

		String accountType;

		AccountType(String accountType) {
			this.accountType = accountType;
		}

	}
}


Step 2: Create your features which matches to regexp in custom implementation:
===============================================================================

feature file:
==============

Feature: Cucumber custom Data types example
	@CustomTypes
  Scenario: test for custom types
    Given a customer has a savings account
    And a customer has a checking account
    
	@CustomTypes
  Scenario: test for custom types
    Given a customer shares his {account_type} to helpDesk
    | checking |
    | savings |


Steps implementation:
======================

	@Given("a customer has a {account_type} account")
	public void testForCustomTypes(AccountType act) {
		System.out.println("Hello your account type is " + act.accountType);
	}

	@Given("a customer shares his \\{account_type} to helpDesk")
	public void a_customer_shares_his_account_type_as(List<AccountType> table) {
		AccountType buildingName = table.get(1);
		System.out.println("Hola " + buildingName.accountType);
	}


Step 3:  execute as normal
============================

Output:
Hello your account type is savings
Hello your account type is checking
Hola savings