Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 结合空安全性和assertNotNull_Kotlin_Kotlin Null Safety - Fatal编程技术网

Kotlin 结合空安全性和assertNotNull

Kotlin 结合空安全性和assertNotNull,kotlin,kotlin-null-safety,Kotlin,Kotlin Null Safety,在测试中,我们通常有assertNotNull,但它不会执行从可空类型到不可空类型的智能转换。我必须这样写: if (test == null) { Assert.fail("") return } 仅使用assertNotNull调用执行智能强制转换是否是一种变通方法?如何处理它?不幸的是,您调用的函数体(包括内联函数)不用于智能强制转换和可空性推断 代码中没有太多可以改进的地方,我只建议一件事:您可以将这些断言语句与函数一起使用。控制流分析考虑了导致Nothing的分支,并

在测试中,我们通常有
assertNotNull
,但它不会执行从可空类型到不可空类型的智能转换。我必须这样写:

if (test == null) {
    Assert.fail("")
    return
}

仅使用
assertNotNull
调用执行智能强制转换是否是一种变通方法?如何处理它?

不幸的是,您调用的函数体(包括内联函数)不用于智能强制转换和可空性推断

代码中没有太多可以改进的地方,我只建议一件事:您可以将这些断言语句与函数一起使用。控制流分析考虑了导致
Nothing
的分支,并由此推断为空:

fun failOnNull(): Nothing = throw AssertionError("Value should not be null")

这也可以在没有函数的情况下编写:
test?:throw-AssertionError(“…”)
,因为
throw
表达式也有类型
Nothing


说到断言失败的更一般情况,可以使用
fail(…):Nothing
函数,这也为控制流分析提供了额外的提示。JUnit
Assert.fail(…)
不是一个
Nothing
函数,但是您可以在模块中找到它或编写自己的函数

test as? SomeType ?: fail("`test` should be an instance of SomeType")
// smart cast works here, `test` is `SomeType`
该库提供了一个简单的解决方案:

kotlin.test.assertNotNull()

由于此函数实现Kotlin契约,因此它支持智能转换:

contract{returns()暗示(实际值!=null)}

示例:

    fun Foo?.assertBar() {
        assertNotNull(this)
        assertEquals(this.bar, 0)
    }
只需确保使用正确的
assertNotNull
import(
import-kotlin.test.assertNotNull

如果尚未使用
kotlin.test
库,请将其添加到项目中:


group:'org.jetbrains.kotlin',name:'kotlin test',version:'1.3.11

非常感谢@Rolf在他的回答中为我指出了图书馆提供的方法

我只想添加并指出,这个方法有一个非null返回类型(即,它返回作为非null对象传递给它的可为null的对象)。因此,如果要在测试中强制展开属性,则可以从中移除,并按如下方式改进测试:

val myProperty = assertNotNull(myObject?.myProperty)
assertEquals("Foo", myProperty.someOtherProperty)

你能提供一个你想改进的更完整的单元测试例子吗?我发现它更容易使用
!!。otherProperty
声明接收器不应为空。@miensol,with
!!。otherProperty
您将获得一个NPE,测试结果将是一个错误,而不是一个失败的断言。不过没什么大不了的。在用Kotlin编写的测试中,强制展开属性是不必要的。请参阅此线程中的我的答案,其中显示了如何使用
kotlin test
库的
assertNotNull
方法来消除强制展开的需要。您也可以执行
test?:fail(“…”)
@mfulton26,但JUnit
Assert.fail()
不是
Nothing
函数,因此,此语句不会产生可空性推断。或者是否有Kotlin测试库附带了
fail():Nothing
函数?
Kotlin.test.fail
来自
Kotlin测试
Kotlin测试junit
的可传递依赖项)。我认为SO可能没有使用
kotlin测试
,尽管这是一个好的观点。
val myProperty = assertNotNull(myObject?.myProperty)
assertEquals("Foo", myProperty.someOtherProperty)