在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
        }

    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...