在测试中,我们通常有assertNotNull
个,但它不会执行从可空类型到不可空类型的智能转换.我必须这样写:
if (test == null) {
Assert.fail("")
return
}
只有assertNotNull
次呼叫才能执行智能投射是一种变通方法吗?你是怎么处理的?
在测试中,我们通常有assertNotNull
个,但它不会执行从可空类型到不可空类型的智能转换.我必须这样写:
if (test == null) {
Assert.fail("")
return
}
只有assertNotNull
次呼叫才能执行智能投射是一种变通方法吗?你是怎么处理的?
不幸的是,您调用的函数体(包括内联函数)不用于智能强制转换和可空性推断.
您的代码中没有太多可以改进的地方,我只建议您做一件事:对于那些断言语句,您可以使用带有Nothing
函数的the Elvis operator.控制流分析将导致Nothing
的分支考虑在内,并由此推断为空性:
fun failOnNull(): Nothing = throw AssertionError("Value should not be null")
val test: Foo? = foo()
test ?: failOnNull()
// `test` is not-null after that
这也可以在没有函数的情况下编写:test ?: throw AssertionError("...")
,因为throw
表达式也有Nothing
类型
说到断言失败的更一般情况,可以使用fail(...): Nothing
函数,这也为控制流分析提供了额外的提示.JUnit Assert.fail(...)
不是Nothing
函数,但您可以在kotlin-test-junit
模块中找到一个,或者编写自己的函数.
test as? SomeType ?: fail("`test` should be an instance of SomeType")
// smart cast works here, `test` is `SomeType`