Boaris
Boaris

Reputation: 5226

Combine null safety and assertNotNull

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

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

Is it a workaround to perform smart cast only with assertNotNull call? How do you deal with it?

Upvotes: 15

Views: 7221

Answers (3)

Adil Hussain
Adil Hussain

Reputation: 32113

Big thank you to @Rolf for pointing me to the assertNotNull method offered by the kotlin-test library in his answer here.

I just want to add and point out that this method has a non-null return type (i.e. it returns the nullable object that is passed into it as a non-null object). So if you are force unwrapping properties in your test, you can move away from this and improve your tests as follows:

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

Upvotes: 0

Rolf ツ
Rolf ツ

Reputation: 8781

The kotlin.test library comes with an easy solution for this:

kotlin.test.assertNotNull()

Because this function implements Kotlin contracts it supports smart casting:

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

Example:

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

Just make sure to use the right assertNotNull import (import kotlin.test.assertNotNull)!

If you don't already use the kotlin.test library, add it to your project:

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

Upvotes: 8

hotkey
hotkey

Reputation: 147951

Unfortunately, the bodies of the functions that you call, including inline functions, are not used for smart casts and nullability inference.

There's not much in your code that can be improved, and I would only suggest one thing: you can use the Elvis operator with a Nothing function for those assertion statements. The control flow analysis takes into account the branches resulting into Nothing and infers nullability from that:

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

val test: Foo? = foo()

test ?: failOnNull()
// `test` is not-null after that

This can be written without a function as well: test ?: throw AssertionError("..."), because a throw expression also has type Nothing.


Speaking of a more general case of failing an assertion, one might use a fail(...): Nothing function, which provides a bonus hint for the control flow analysis as well. The JUnit Assert.fail(...) is not a Nothing function, but you can find one in the kotlin-test-junit module or write your own one.

test as? SomeType ?: fail("`test` should be an instance of SomeType")
// smart cast works here, `test` is `SomeType`

Upvotes: 13

Related Questions