In this post we will discuss all new cucumber 5 released couple of weeks before and its awesome new way to use Cucumber expression. Cucumber expressions released way back in Cucumber-JVM 3.0.0 With it came the ability to register parameter- and data table-types by implementing the TypeRegistryConfigurer
.
The TypeRegistryConfigurer
however is not part of the glue. This made it impossible to access the test context. With cucumber-java
this is now possible by using the @ParameterType
, @DataTableType
and @DocStringType
annotations. This allows parameter-, data table- and docstring types to be mapped to objects which can only be created inside the test context.
Here is how the scenario looks like
Scenario: Perform an misc operation Given I login as admin |username|password| |admin |[blank] | And I have few books in hand such as java, js, csharp
@DataTableType
An replacement of TableEntryTransformer and TableCellTransformer and the code looks something like this
@DataTableType(replaceWithEmptyString = "[blank]") public UserInfo convert(Map<String, String> entry) { return new UserInfo( entry.get("username"), entry.get("password").concat("@#$@#$@#@#$") ); }
@ParameterType
Parameter type annotation will helps work with any parameters passed within the step definition
@ParameterType("[^\"]*") public List<String> book(String bookName) { return Arrays.asList(bookName.split(",")); }
And its step definition looks like this
@And("I have few books in hand such as {book}") public void iHaveFewBooksInHandSuchAsJavaJsCsharp(List<String> books) { System.out.println(books.get(2)); }
Please note the above {book} in the @And attribute in the step definition which calls the book method of the @ParameterType
@DocStringType
This is a new feature introduced in Cucumber 5 which does more magics which allow DocStrings in Steps to be transformed into an ObjectAll new
The DocString step looks something like this
Given some more information """json { "Name": "Karthik", "Company": "ExecuteAutomation", "Living": "New Zealand" } """
And the implementation of this code looks like this
@DocStringType public JsonNode json(String docString) throws JsonProcessingException { return objectMapper.readTree(docString); } @Given("some more information") public void someMoreInformation(JsonNode jsonNode) { var name = jsonNode.get("Name"); var company = jsonNode.get("Company"); System.out.println("Name " + name + ", Company " + company); }
Here is the complete video of the above discussion
Thanks for reading the article and watching the video !
Please leave your valuable comments on the post and video if you think there needs any improvement or I missed anything to add.
Thanks,
Karthik KK
Hi Karthik,
In case of test failure how to add meaningful message along with the technical errors in the cucumber.json report. The same json report is being used by Jenkins cucumber html report plugin.