Skip to content

Commit e6d42c8

Browse files
committed
add documentation about localized transformers
1 parent a22c82f commit e6d42c8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

cucumber-java/README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,55 @@ public class DataTableStepDefinitions {
329329
}
330330
```
331331

332+
### Localized Transformers
333+
334+
Combining the [Before hook](#before--after) and the Scenario's language offers custom transformation that respects the
335+
language of the feature file. For example, localized features about summer solstice may provide the date "21 kesäkuuta
336+
2025" (Finnish) or "21 juin 2025" (French). Parsing these dates requires an according `DateTimeFormatter`, either within
337+
a default transformer method or within a named type.
338+
339+
```java
340+
package com.example.app;
341+
342+
import io.cucumber.java.Before;
343+
import io.cucumber.java.DefaultParameterTransformer;
344+
import io.cucumber.java.ParameterType;
345+
import io.cucumber.java.Scenario;
346+
347+
import java.lang.reflect.Type;
348+
import java.time.LocalDate;
349+
import java.time.format.DateTimeFormatter;
350+
import java.util.Locale;
351+
352+
public class TransformerDefinitions {
353+
354+
private DateTimeFormatter formatter;
355+
356+
@Before
357+
public void updateFormatter(final Scenario scenario) {
358+
String language = scenario.getLanguage();
359+
Locale locale = new Locale.Builder().setLanguage(language).build();
360+
formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(locale);
361+
}
362+
363+
@DefaultParameterTransformer
364+
public Object transform(final String value, final Type type)
365+
throws Exception {
366+
if (LocalDate.class.equals(type)) {
367+
return LocalDate.parse(value.toString(), formatter);
368+
} else {
369+
throw new UnsupportedOperationException("Can't transform '" + value + "' to " + type);
370+
}
371+
}
372+
373+
@ParameterType(name = "date", value = "\\d{1,2} \\w+ \\d{4}")
374+
public LocalDate parseLocalDate(String value) {
375+
return LocalDate.parse(value, formatter);
376+
}
377+
378+
}
379+
```
380+
332381
### Empty Cells
333382

334383
Data tables in Gherkin cannot represent null or an empty string unambiguously. Cucumber will interpret empty cells as

0 commit comments

Comments
 (0)