You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cucumber无法将字符串转换为Recipe类对象报错如何解决?

问题原因
  • 缺失自定义类型转换逻辑:Cucumber默认仅支持字符串转基础数据类型(如字符串、数字、布尔值等),你在正则中捕获到的Recipe4是字符串格式,Cucumber不知道如何将其转换为你自定义的Recipe类实例,因此直接抛出转换异常。
  • Step定义逻辑无效:你当前的Step方法中第一行就执行了recipe = new Recipe(),直接覆盖了Cucumber尝试传入的参数,就算解决了类型转换问题,你捕获到的Recipe4内容也完全不会被用到,和你后续硬编码设置属性的逻辑完全脱节。
解决方案

方案1:保留动态匹配逻辑,添加类型转换器

如果你需要根据feature中填写的不同食谱名称自动生成对应Recipe对象,可通过Cucumber的参数类型注解实现转换逻辑(适用于Cucumber 6及以上版本):

  1. 新增自定义参数类型转换器,可放在任意Step类或者专门的转换配置类中:
@ParameterType(".*")
public Recipe recipe(String recipeName) {
    Recipe recipe = new Recipe();
    // 可根据捕获到的食谱名称匹配对应属性配置
    if ("Recipe4".equals(recipeName)) {
        recipe.setName("Hot Chocolate");
        recipe.setAmtChocolate("4");
        recipe.setAmtCoffee("0");
        recipe.setAmtMilk("1");
        recipe.setAmtSugar("1");
        recipe.setPrice("65");
    }
    // 其他食谱的匹配逻辑可在此处扩展
    return recipe;
}
  1. 改造原有StepDef方法,删除硬编码创建Recipe的逻辑:
@When("{recipe} is added to the recipe book")
public void addRecipeTest(Recipe recipe) throws RecipeException {
    assertEquals(true, coffeeMaker.addRecipe(recipe));
    assertEquals(coffeeMakerMain.getMode(), Mode.WAITING);
    System.out.println("Recipe is added");
}

方案2:不需要动态匹配,直接简化Step定义

如果你只是需要固定执行添加热巧克力的逻辑,不需要复用这个Step匹配其他食谱,可以直接删掉正则捕获组,不需要传Recipe参数:

@When("Recipe4 is added to the recipe book")
public void addRecipeTest() throws RecipeException {
    Recipe recipe = new Recipe();
    recipe.setName("Hot Chocolate");
    recipe.setAmtChocolate("4");
    recipe.setAmtCoffee("0");
    recipe.setAmtMilk("1");
    recipe.setAmtSugar("1");
    recipe.setPrice("65");
    assertEquals(true, coffeeMaker.addRecipe(recipe));
    assertEquals(coffeeMakerMain.getMode(), Mode.WAITING);
    System.out.println("Recipe is added");
}

内容的提问来源于stack exchange,提问作者aish007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:18:03