kotlinfixture icon indicating copy to clipboard operation
kotlinfixture copied to clipboard

Override nullability strategy

Open mahdibohloul opened this issue 2 years ago • 2 comments

Hi there,

According to your document about overriding nullability strategy, I have an issue with it in nullable properties.

By default, when the library comes across a nullable type, such as String? it will randomly return a value or null. This can be overridden by setting a nullability strategy.

I have a data class like:

data class Order(val id: String? = null, /*with some other fields*/ )

And I'm using KotlinFixture to write tests like that:

val order = kotlinFixture {
      nullabilityStrategy(NeverNullStrategy)
      //Other configuration
    } <Order>()

I expected the id attribute to always have a value. But this is not the case and sometimes it is null and the test is not deterministic and sometimes it is passed and sometimes it is not.

My fixture version: 1.2.0

mahdibohloul avatar Dec 18 '21 14:12 mahdibohloul

Any update about the issue?

mahdibohloul avatar Mar 02 '22 07:03 mahdibohloul

Hi sorry @mahdibohloul I missed seeing your issue previously.

The issue comes as you have both null types and default values. So while the null strategy will ensure it won't generate a null at random, the optional strategy will randomly choose between generating a value or using the default value.

What this means is for this scenario you also need to override the optionalStrategy to be NeverOptionalStrategy:

private val fixture = kotlinFixture {
    nullabilityStrategy(NeverNullStrategy)
    optionalStrategy(NeverOptionalStrategy)
}

mattmook avatar Mar 05 '22 20:03 mattmook