我最近在项目中已升级到Cucumber-jvm的最新4.x版本,以利用Cucumber的并行执行功能。但是我现在面临着将自定义数据类型作为参数的问题。早些时候,我们有一个称为Transformer
的接口,我们可以为自定义数据类型实现,现在在我发现的TypeRegistryConfigurer
接口的最新版本中,需要实现。但这并没有像我预期的那样认识到这一步骤。详细信息如下:
小黄瓜步骤:
Given user gets random(3,true,true) parameter
stepdefinition:
@Given("user gets {random} parameter")
public void paramTest(RandomString randomString) {
System.out.println(randomString.string);
}
随机串类:
public class RandomString {
public String string;
public RandomString(String string) {
Matcher m = Pattern.compile("random\((.?)\)").matcher(string);
String t = "";
while (m.find()) {
t = m.group(1);
}
boolean isAlpha = true, isNum = true;
if (t.length() > 0) {
String[] placeholders = t.split(",");
if (placeholders.length == 3) {
int count = Integer.parseInt(placeholders[0]);
isAlpha = Boolean.valueOf(placeholders[1]);
isNum = Boolean.valueOf(placeholders[2]);
this.string = string.replaceAll("random(.*)", RandomStringUtils.random(count, isAlpha, isNum));
}
}
this.string = string.replaceAll("random(.*)", RandomStringUtils.random(3, isAlpha, isNum));
}
}
typeregistrympl:
public class TypeRegistryConfiguration implements TypeRegistryConfigurer {
@Override
public Locale locale() {
return Locale.ENGLISH;
}
@Override
public void configureTypeRegistry(TypeRegistry typeRegistry) {
typeRegistry.defineParameterType(new ParameterType<>(
"random",
"random([0-9],true|false,true|false)",
RandomString.class,
RandomString::new)
);
}
}
您的字符串random(3,true,true)
与以下方式不匹配:
typeRegistry.defineParameterType(new ParameterType<>(
"random",
"random([0-9],true|false,true|false)",
RandomString.class,
RandomString::new)
);
您可以通过创建模式并测试它来验证这一点:
import java.util.regex.Pattern;
class Scratch {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("random([0-9],true|false,true|false)");
// prints out false
System.out.println(pattern.matcher("random(3,true,true)").matches());
}
}
您也没有在RandomString
中使用匹配模式。
我在试验后找到了解决方案,并在Cucumber-JVM项目中的某些单元测试中击中并浏览了一些示例。
修改 stepdef :
@Given("user gets {random} parameter")
public void paramTest(String randomString) {
System.out.println(randomString.string);
}
typeregistryconfigurer实现:
import cucumber.api.TypeRegistry;
import cucumber.api.TypeRegistryConfigurer;
import io.cucumber.cucumberexpressions.CaptureGroupTransformer;
import io.cucumber.cucumberexpressions.ParameterType;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Locale;
public class TypeRegistryConfiguration implements TypeRegistryConfigurer {
@Override
public Locale locale() {
return Locale.ENGLISH;
}
@Override
public void configureTypeRegistry(TypeRegistry typeRegistry) {
typeRegistry.defineParameterType(new ParameterType<>(
"random",
"random\(([0-9]+),(true|false),(true|false)\)",
String.class,
new CaptureGroupTransformer<>() {
@Override
public String transform(String[] args) {
return RandomStringUtils.random(Integer.parseInt(args[0]), Boolean.valueOf(args[1]), Boolean.valueOf(args[2]));
}
})
);
}
}