结合null安全性和assertNotNull

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

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

使用assertNotNull调用来执行智能转换是否是一种解决方法? 你如何处理?

不幸的是,你调用的函数的主体,包括内联函数,不能用于智能转换和可空性推断。

代码中没有太多可以改进的地方,我只能提出一点建议:对于这些断言语句,可以使用Elvis操作符的Nothing函数。 控制流分析考虑到分支产生为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`