Skip to content

Commit

Permalink
Allow non-null factory to be used for nullable types (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmook authored Nov 13, 2019
1 parent 269e7ba commit 5051369
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,27 @@ package com.appmattus.kotlinfixture.resolver
import com.appmattus.kotlinfixture.Context
import com.appmattus.kotlinfixture.Unresolved
import com.appmattus.kotlinfixture.config.DefaultGenerator
import com.appmattus.kotlinfixture.decorator.nullability.wrapNullability
import kotlin.reflect.KType
import kotlin.reflect.full.withNullability

internal class FactoryResolver : Resolver {

@Suppress("ReturnCount")
override fun resolve(context: Context, obj: Any): Any? {

if (obj is KType) {
context.configuration.factories[obj]?.let {
return with(DefaultGenerator(context)) { it() }
}

if (obj.isMarkedNullable) {
context.configuration.factories[obj.withNullability(false)]?.let {
return context.wrapNullability(obj) {
with(DefaultGenerator(context)) { it() }
}
}
}
}

return Unresolved
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package com.appmattus.kotlinfixture.resolver

import com.appmattus.kotlinfixture.TestContext
import com.appmattus.kotlinfixture.Unresolved
import com.appmattus.kotlinfixture.assertIsRandom
import com.appmattus.kotlinfixture.config.Configuration
import com.appmattus.kotlinfixture.config.ConfigurationBuilder
import com.appmattus.kotlinfixture.typeOf
Expand All @@ -36,7 +37,7 @@ class FactoryResolverTest {
}

@Test
fun `Factory returned when mapping found`() {
fun `Factory returned when non-null mapping found for non-null`() {
val configuration = ConfigurationBuilder().apply {
factory<Number> { 12 }
}.build()
Expand All @@ -56,4 +57,36 @@ class FactoryResolverTest {
assertTrue(context.resolve(typeOf<Number>()) in 1..5)
}
}

@Test
fun `Unresolved returned when non-nullable requested and only nullable factory found`() {
val configuration = ConfigurationBuilder().apply {
factory<Number?> { 12 }
}.build()
val context = TestContext(configuration, FactoryResolver())

assertEquals(Unresolved, context.resolve(typeOf<Number>()))
}

@Test
fun `Factory returned when nullable mapping found for nullable`() {
val configuration = ConfigurationBuilder().apply {
factory<Number?> { 12 }
}.build()
val context = TestContext(configuration, FactoryResolver())

assertEquals(12, context.resolve(typeOf<Number?>()))
}

@Test
fun `Random nullability returned when non-null mapping found for nullable`() {
val configuration = ConfigurationBuilder().apply {
factory<Number> { 12 }
}.build()
val context = TestContext(configuration, FactoryResolver())

assertIsRandom {
context.resolve(typeOf<Number?>()) == null
}
}
}

0 comments on commit 5051369

Please sign in to comment.