在测试中,我们通常有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`

Kotlin相关问答推荐

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何让 LocalDateTime.parse 拒绝 24:00 时间

为什么使用 return instance ?: synchronized(this) { instance ?: PreferenceParameterState(context) } 时无法获得单例?

Kotlin中是否可以混合使用推断和显式的通用类型参数?

使用 Jetpack Compose 使用参数导航

为什么这两个 Kotlin 协程函数不一样?

Eclipse:无法安装 Kotlin 插件

为什么我们在 kotlin 中需要 noinline?

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

对列表中数字的子集求和

jetpack compose 将参数传递给 viewModel

在 Kotlin 中通过反射获取 Enum 值

包括登录Elvis operator?

调用单元测试验证伴随对象方法

Kotlin 创建snackbar

Kotlin惰性默认属性

Kotlin解构when/if语句

android Room 将 Null 作为非 Null 类型返回

WebFlux 功能:如何检测空 Flux 并返回 404?

Kotlin:测试中的 java.lang.NoSuchMethodError