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

如何在Cucumber 7.8.1(Kotlin)中注册自定义Money参数类型?

解决Cucumber Kotlin自定义Money类型注册失效问题

针对你使用Cucumber 7.8.1时,自定义Money类型注册未生效的问题,按以下步骤调整即可解决:

1. 完善自定义Money类的解析逻辑

确保你的Money类具备从带$符号的字符串解析实例的能力,比如:

import java.math.BigDecimal

data class Money(val amount: BigDecimal) {
    companion object {
        fun fromString(value: String): Money {
            // 剔除$符号后转换为BigDecimal
            val cleanValue = value.replace("$", "").toBigDecimal()
            return Money(cleanValue)
        }
    }
}

2. 实现TypeRegistryConfigurer注册类型转换器

Cucumber 7.x需通过TypeRegistryConfigurer配置类型转换规则,创建如下类并确保它在Cucumber扫描范围内(与步骤定义同包即可):

import io.cucumber.core.api.TypeRegistry
import io.cucumber.core.api.TypeRegistryConfigurer
import io.cucumber.java.ParameterType
import java.util.Locale

class MoneyTypeConfig : TypeRegistryConfigurer {
    override fun configureTypeRegistry(typeRegistry: TypeRegistry) {
        // 注册名为"money"的参数类型,匹配$开头的金额格式
        typeRegistry.defineParameterType(
            ParameterType(
                name = "money",
                regexp = "\\$\\d+(\\.\\d{2})?",
                type = Money::class.java,
                transformer = { input: String -> Money.fromString(input) }
            )
        )
    }

    override fun locale(): Locale {
        return Locale.ENGLISH
    }
}

3. 修正步骤定义的参数引用方式

直接用注册的参数类型名{money}替代硬编码正则,让Cucumber自动匹配转换:

@Given("I have deposited a {money} in my account")
fun `I have deposited a $ in my account`(money: Money) {
    account = Account()
    account.deposit(amount = money)
    assertEquals(money, account.getBalance(), "Incorrect Account Balance")
}

4. 适配其他场景步骤

对剩余步骤做同样调整,统一使用{money}引用:

@When("I request {money}")
fun `I request $`(amount: Money) {
    account.withdraw(amount)
}

@Then("{money} should be dispensed")
fun `$ should be dispensed`(amount: Money) {
    // 此处添加金额发放验证逻辑
}

完成以上调整后,Cucumber就能自动将场景中$100.00、$20这类字符串转换为你的自定义Money对象。

内容的提问来源于stack exchange,提问作者Saher Al-Sous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:05:26