[Kotlin] Parameter specified as non-null is null: method kotlinx.serialization.encoding.AbstractEncoder.encodeStringElement, parameter value java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.encoding.AbstractEncoder.encodeStringElement, parameter value



1. Problem

When i make test code on Spring boot & kotlin, i met this problem. I used fixture and that made some data class, but that fixture made problem! The problem arose because of null value. In that time, fixture makes null value on my code. How can i avoid null properties in Kotlin?

Parameter specified as non-null is null: method kotlinx.serialization.encoding.AbstractEncoder.encodeStringElement, parameter value
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.encoding.AbstractEncoder.encodeStringElement, parameter value
	at kotlinx.serialization.encoding.AbstractEncoder.encodeStringElement(AbstractEncoder.kt)

And i saw below issue, because i used JsonDecoding!

kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator ('null')

That is my code. My code makes error on json.encodeToString. Because fixture() makes null member field, that makes this problem!!

init {
    val fixture = kotlinFixture {}
    given("given") {
        continually(30.seconds){
            val moneyClass = fixture<MoneyClass>()

            `when`("when") {
                val json = Json { serializersModule = module }
                val json.encodeToString(PolymorphicSerializer(CashClass::class), moneyClass)

                // some code
                // ~~~ 

                then("then") {
                    // some result
                    1 shouldbe 1
                }
            }
        }
    }
}

2. Solution

The solution is change fixture setting! I use nullabilityStrategy(NeverNullStrategy)! This solve problem so well. When you try this, fixture cannot make null value.

val fixture = kotlinFixture {
    nullabilityStrategy(NeverNullStrategy)
}

Below is configured code!

init {
    val fixture = kotlinFixture {
        nullabilityStrategy(NeverNullStrategy)
    }
    given("given") {
        continually(30.seconds){
            val moneyClass = fixture<MoneyClass>()

            `when`("when") {
                val json = Json { serializersModule = module }
                val json.encodeToString(PolymorphicSerializer(CashClass::class), moneyClass)

                // some code
                // ~~~ 

                then("then") {
                    // some result
                    1 shouldbe 1
                }
            }
        }
    }
}