Created
August 25, 2020 15:08
-
-
Save michellescripts/b52444c1c368e9da05bdc122e3685430 to your computer and use it in GitHub Desktop.
kotlin maker example for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Make function (create in test directory) | |
inline fun <reified T> make(): T { | |
return makeInstanceOfClass(T::class) as T | |
} | |
fun makeInstanceOfClass(clazz: KClass<*>): Any? { | |
val primitive = makePrimitiveOrNull(clazz) | |
if (primitive != null) { | |
return primitive | |
} | |
val constructors = clazz.constructors | |
.sortedBy { it.parameters.size } | |
for (constructor in constructors) { | |
val arguments = constructor.parameters | |
.map { param -> | |
param.takeUnless { it.type.isMarkedNullable } | |
?.let { makeInstanceOfClass(it.type.classifier as KClass<*>) } | |
} | |
.toTypedArray() | |
try { | |
return constructor.call(*arguments) | |
} catch (e: Throwable) { | |
} | |
} | |
throw NoUsableConstructor(clazz) | |
} | |
private fun makePrimitiveOrNull(clazz: KClass<*>): Any? = when (clazz) { | |
Int::class -> 0 | |
Long::class -> 0L | |
Double::class -> 0.0 | |
String::class -> "" | |
Boolean::class -> false | |
UUID::class -> UUID.randomUUID() | |
List::class -> emptyList<Any>() | |
Set::class -> emptySet<Any>() | |
Map::class -> emptyMap<Any, Any>() | |
LocalDate::class -> LocalDate.now() | |
LocalDateTime::class -> LocalDateTime.now() | |
TrackingAction::class -> TrackingAction.CLEAN_CLICKED | |
else -> null | |
} | |
class NoUsableConstructor(clazz: KClass<*>) : Error("Could not find a constructor for class: ${clazz.simpleName}") | |
-------------------------- Example | |
## Entity | |
data class User( | |
val id: UUID, | |
val firstName: String, | |
val lastName: String, | |
val email: String, | |
val active: Boolean | |
) | |
## Initialize an entity with "primative" values | |
val user = make<User>() | |
Creates: | |
User( | |
id = <random UUID>, | |
firstName = "", | |
lastName = "", | |
email = "", | |
active = false | |
) | |
## Initialize an entity with specfic values | |
-- you can set as many properties as you'd like (Tip: set only what you're testing!) | |
val user = make<User>().copy(firstName = "Michelle") | |
Creates: | |
User( | |
id = <random UUID>, | |
firstName = "Michelle", | |
lastName = "", | |
email = "", | |
active = false | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment