[Kotlin] Recursive non-null generation for Kotlin nullable types? #1218
-
Hi there! I'm using the Kotlin plugin for FixtureMonkey. I would like to configure it so that never produces null values and recursively, even for Kotlin nullable types like Is that possible? I tried using a builder with Could someone confirm? Is that possible to enforce non-null generation on nullable types? Thanks! 🙂 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
For anyone interested I found the way to configure it. Though the code is in Kotlin, it works for both Kotlin and Java complex nested objects: /**
* Generates a FixtureMonkey builder for the specified type, using the FixtureMonkey instance configured for Kotlin.
*
* @param noNulls If true, the generated instance fields will not contain any null values (recursive). Defaults to
* false as the option makes more sense for Java objects.
* @return A test fixture builder that allows to customize the generated object.
*/
inline fun <reified A> fixtBuilder(noNulls: Boolean = false) =
fixtMonkeyBuilder
//.defaultNotNull(noNulls) // <-- this is not honored in Kotlin nullable types, e.g. String?
.defaultNullInjectGenerator { if (noNulls) NOT_NULL_INJECT else DEFAULT_NULL_INJECT }
.build()
.giveMeBuilder<A>()
/**
* A FixtureMonkey builder configured for Kotlin. The builder can be customized for specific needs, such as
* registering specific subtype generation via `InterfacePlugin`.
*
* Optionally, you can install the IntelliJ plugin 'Fixture Monkey Helper' to get enhanced DX.
*/
val fixtMonkeyBuilder: FixtureMonkeyBuilder = FixtureMonkey.builder()
.plugin(KotlinPlugin())
.useExpressionStrictMode() // runtime failure if string expressions are not valid Test code: class FixtureMonkeyTest {
private data class ComplexObject(
val nullableString: String?,
val nullableNestedObject: NestedObject?,
) {
private data class NestedObject(
val nestedNullableString: String?,
)
}
@RepeatedTest(10)
fun `should generate complex objects without null fields recursively`() {
val complexObject = fixtBuilder<ComplexObject>(true)
.sample()
assertThat(complexObject)
.isNotNull
.hasNoNullFieldsOrProperties()
.usingRecursiveAssertion()
.hasNoNullFields()
}
} |
Beta Was this translation helpful? Give feedback.
For anyone interested I found the way to configure it. Though the code is in Kotlin, it works for both Kotlin and Java complex nested objects: