如何解决在intellij中使用kotest时“该表达式未使用”
使用 Kotest 编写的这个 kotlin 测试,IntelliJ 显示警告“表达式未使用”并且语法着色不起作用。 此外,在运行测试时,未找到测试。
class TalentMatchServiceSpec : StringSpec() {
init {
"add 3 to 2 should give 5"
{
// Given integers 2 and 3
val two = 2
val three = 3
// When adding both numbers
val sum = two + three
// Then the result is 5
sum shouldBe 5
}
}
}
解决方法
@Thomas Martin 的回答是正确的,但您问为什么它会有所不同。
Kotest 中的 SpringSpec
依赖于一些 Kotlin DSL 功能来工作。让我们通过从头开始构建相同的函数来演示。
我们将从使用 Kotlin 的扩展函数开始。这允许我们向我们无法控制的类添加函数。
所以,
fun String.test(test: () -> Unit)
那么我们可以在任何字符串上调用这个测试函数:
"this is a test".test({ 1 + 2 shouldBe 3 })
其次,Kotlin 允许将任何最终的 lambda arg 带入括号之外。所以 foo(arg,arg2,arg3,lambda)
可以变成 foo(arg,arg3) lambda
。这意味着我们可以将测试编写为:
"this is a test".test { 1 + 2 shouldBe 3 }
接下来,我们可以将函数标记为中缀,然后我们不需要使用点来调用它们。所以我们的测试函数变成了:
infix fun String.test(test: () -> Unit)
我们的测试现在看起来像:
"this is a test" test { 1 + 2 shouldBe 3 }
最后,任何名为 invoke
并标记为运算符函数的函数都可以在没有函数名称的情况下调用。因此,类 Foo 中的 operator fun invoke(a: String,b: String)
可以作为常规 Foo.invoke(a,b)
或仅作为 Foo(a,b)
调用。
所以把所有这些放在一起,我们的最终测试函数看起来像:
operator fun String.invoke(test: () -> Unit)
我们的测试结果如下:
"this is a test" { 1 + 2 shouldBe 3 }
或者更有可能,
"this is a test" {
1 + 2 shouldBe 3
}
如果将大括号移到下一行,就像在您的原始问题中一样,它看起来就像一个字符串,后跟一个无关的 lambda 块。两种不同的表达方式。
,把左花括号放在“加3到2应该给5”之后,就像这样:
class TalentMatchServiceSpec : StringSpec() {
init {
"add 3 to 2 should give 5" {
// Given integers 2 and 3
val two = 2
val three = 3
// When adding both numbers
val sum = two + three
// Then the result is 5
sum shouldBe 5
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。