Combining Null Security and assertNotNull

In a test, we usually have assertNotNull , but it does not perform smart cast from null to non-nullable. I should write something like this:

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

Is this a workaround to perform smart cast only when calling assertNotNull ? How do you deal with this?

+11
kotlin
source share
2 answers

Unfortunately, the bodies of the functions you call, including the built-in functions, are not used for smart casts and nullifications.

There is little that can be improved in your code, and I would suggest only one thing: you can use the Elvis operator with the Nothing function for these statements. Analysis of the control flow takes into account the branches that occur in Nothing and deduces from this zeroing:

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

 val test: Foo? = foo() test ?: failOnNull() // 'test' is not-null after that 

It can also be written without a function: test?: throw AssertionError("...") , because the throw expression is also of type Nothing .


Speaking of a more general case of a statement failure, you can use the fail(...): Nothing function, which also provides a hint for analyzing the control flow. JUnit Assert.fail(...) not a Nothing function, but you can find it in kotlin-test-junit or write your own.

 test as? SomeType ?: fail("'test' should be an instance of SomeType") // smart cast works here, 'test' is 'SomeType' 
+9
source share

The kotlin.test library comes with a simple solution for this:

kotlin.test.assertNotNull()

Since this function implements Kotlin contracts, it supports smart casts:

contract { returns() implies (actual != null) }

Example:

  fun Foo?.assertBar() { assertNotNull(this) assertEquals(this.bar, 0) } 

Just make sure you are using the correct assertNotNull import kotlin.test.assertNotNull ( import kotlin.test.assertNotNull )!

If you are not using the kotlin.test library kotlin.test , add it to your project:

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

0
source share

All Articles