Skip to content

Commit

Permalink
Merge pull request #1134 from k163377/speed-up
Browse files Browse the repository at this point in the history
Minor performance improvements to MockInjector
  • Loading branch information
Raibaz committed Aug 29, 2023
2 parents 69e6265 + 7408e41 commit a9cedf1
Showing 1 changed file with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ class MockInjector(
val injectImmutable: Boolean,
val overrideValues: Boolean
) {
private companion object {
private val sortCriteria = compareBy<KFunction<Any>>(
{ -it.parameters.size },
{ fn -> fn.parameters.joinToString(",") { it.type.toString() } }
)
}

fun constructorInjection(type: KClass<*>): Any {
val firstMatching = findMatchingConstructor(type)
?: throw MockKException("No matching constructors found:\n" + type.constructors.joinToString("\n") { it.constructorToStr() })
Expand Down Expand Up @@ -45,17 +52,15 @@ class MockInjector(

private fun injectViaConstructor(firstMatching: KFunction<Any>): Any {
return firstMatching.valueParameters
.associateWith { matchParameter(it) }
.filterNot { it.value == null }
.fold(mutableMapOf<KParameter, Any>()) { acc, cur ->
acc.apply {
matchParameter(cur)?.let { this[cur] = it }
}
}
.let { firstMatching.callBy(it) }
}

private fun findMatchingConstructor(type: KClass<*>): KFunction<Any>? {
val sortCriteria = compareBy<KFunction<Any>>(
{ -it.parameters.size },
{ fn -> fn.parameters.joinToString(",") { it.type.toString() } }
)

return type.constructors.sortedWith(sortCriteria)
.firstOrNull { tryMatchingParameters(it.valueParameters) }
}
Expand Down

0 comments on commit a9cedf1

Please sign in to comment.