Created
November 2, 2018 05:43
-
-
Save oleksiyp/a8b8a10bd9ba7324b5fec9f910ae5bdd to your computer and use it in GitHub Desktop.
"MockK: intentions" example about matchers
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
data class ListWithoutOrderMatcher<T>( | |
val expectedList: List<T>, | |
val refEq: Boolean | |
) : Matcher<List<T>> { | |
val map = buildCountsMap(expectedList, refEq) | |
override fun match(arg: List<T>?): Boolean { | |
if (arg == null) return false | |
return buildCountsMap(arg, refEq) == map | |
} | |
private fun buildCountsMap(list: List<T>, ref: Boolean): Map<Any?, Int> { | |
val map = mutableMapOf<Any?, Int>() | |
for (item in list) { | |
val key = when { | |
item == null -> nullKey | |
refEq -> InternalPlatform.ref(item) | |
else -> item | |
} | |
map.compute(key, { _, value -> (value ?: 0) + 1 }) | |
} | |
return map | |
} | |
override fun toString() = "matchListWithoutOrder($expectedList)" | |
@Suppress("UNCHECKED_CAST") | |
override fun substitute(map: Map<Any, Any>): Matcher<List<T>> { | |
return copy(expectedList = expectedList.map { map.getOrDefault(it as Any?, it) } as List<T>) | |
} | |
companion object { | |
val nullKey = Any() | |
} | |
} | |
inline fun <reified T : List<E>, E : Any> MockKMatcherScope.matchListWithoutOrder( | |
vararg items: E, | |
refEq: Boolean = true | |
): T = match(ListWithoutOrderMatcher(listOf(*items), refEq)) | |
@Test | |
fun test() { | |
class MockCls { | |
fun op(a: List<Int>) = a.reversed() | |
} | |
val mock = mockk<MockCls>() | |
every { mock.op(any()) } returns listOf(5, 6, 9) | |
println(mock.op(listOf(1, 2, 3))) | |
verify { mock.op(matchListWithoutOrder(3, 2, 1)) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment