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

Kotest勾股三元组示例报错:函数调用错误与类型推断失败

解决方案:Kotest 5.5.0 中 forAll/withData 使用问题修复

问题根源分析

  • forAll 参数不匹配:直接传入自定义的PythagoreanTriple实例,但Kotest的forAll要求参数是Row1/Row2等专用行类型,而非自定义数据类。
  • withData 找不到:缺少对应的导入(已添加的kotest-runner-junit5-jvm模块已包含withData所需代码,无需额外依赖)。
  • 类型推断失败:因forAll参数类型不匹配,导致Kotlin无法解构推断(a,b,c)的类型。

方案1:使用 forAll + Row1 适配自定义数据类

修改代码,用Row1包装PythagoreanTriple实例,同时明确lambda参数类型:

import io.kotest.core.spec.style.FunSpec
import io.kotest.data.Row1
import io.kotest.data.forAll
import io.kotest.matchers.shouldBe

data class PythagoreanTriple(
    val a: Int,
    val b: Int,
    val c: Int
)

class MyTests : FunSpec({
    context("Pythagorean triples tests") {
        forAll(
            Row1(PythagoreanTriple(3, 4, 5)),
            Row1(PythagoreanTriple(6, 8, 10)),
            Row1(PythagoreanTriple(8, 15, 17)),
            Row1(PythagoreanTriple(7, 24, 25))
        ) { triple: PythagoreanTriple ->
            val (a, b, c) = triple
            isPythagoreanTriple(a, b, c) shouldBe true
        }
    }
})

fun isPythagoreanTriple(a: Int, b: Int, c: Int): Boolean = a * a + b * b == c * c

方案2:使用 withData(更适合自定义数据类场景)

withData是Kotest中处理参数化测试的更直观方式,支持直接传入自定义对象,只需确保正确导入:

import io.kotest.core.spec.style.FunSpec
import io.kotest.core.spec.style.scopes.withData
import io.kotest.matchers.shouldBe

data class PythagoreanTriple(
    val a: Int,
    val b: Int,
    val c: Int
)

class MyTests : FunSpec({
    context("Pythagorean triples tests") {
        withData(
            PythagoreanTriple(3, 4, 5),
            PythagoreanTriple(6, 8, 10),
            PythagoreanTriple(8, 15, 17),
            PythagoreanTriple(7, 24, 25)
        ) { (a, b, c) ->
            isPythagoreanTriple(a, b, c) shouldBe true
        }
    }
})

fun isPythagoreanTriple(a: Int, b: Int, c: Int): Boolean = a * a + b * b == c * c

额外说明

若想直接传递多个单独参数(无需自定义数据类),可以用Row3包装三元组,这种方式更简洁:

import io.kotest.core.spec.style.FunSpec
import io.kotest.data.Row3
import io.kotest.data.forAll
import io.kotest.matchers.shouldBe

class MyTests : FunSpec({
    context("Pythagorean triples tests") {
        forAll(
            Row3(3, 4, 5),
            Row3(6, 8, 10),
            Row3(8, 15, 17),
            Row3(7, 24, 25)
        ) { a, b, c ->
            isPythagoreanTriple(a, b, c) shouldBe true
        }
    }
})

fun isPythagoreanTriple(a: Int, b: Int, c: Int): Boolean = a * a + b * b == c * c

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 03:40:33