Skip to content

Instantly share code, notes, and snippets.

@oleksiyp
Created November 2, 2018 06:24
Show Gist options
  • Save oleksiyp/e8b8b4e08d97af29f3b3f642a4400a11 to your computer and use it in GitHub Desktop.
Save oleksiyp/e8b8b4e08d97af29f3b3f642a4400a11 to your computer and use it in GitHub Desktop.
"MockK: intentions" example about composite matchers
/**
* Boolean logic "AND" and "OR" matcher composed of two other matchers
*/
data class AndOrMatcher<T : Any>(
val and: Boolean,
val first: T,
val second: T
) : Matcher<T>, CompositeMatcher<T>, CapturingMatcher {
override val operandValues: List<T>
get() = listOf(first, second)
override var subMatchers: List<Matcher<T>>? = null
override fun match(arg: T?): Boolean =
if (and)
subMatchers!![0].match(arg) && subMatchers!![1].match(arg)
else
subMatchers!![0].match(arg) || subMatchers!![1].match(arg)
override fun substitute(map: Map<Any, Any>): Matcher<T> {
val matcher = copy(
first = first.internalSubstitute(map),
second = second.internalSubstitute(map)
)
val sm = subMatchers
if (sm != null) {
matcher.subMatchers = sm.map { it.substitute(map) }
}
return matcher
}
override fun capture(arg: Any?) {
captureSubMatchers(arg)
}
override fun toString(): String {
val sm = subMatchers
val op = if (and) "and" else "or"
return if (sm != null)
"$op(${sm[0]}, ${sm[1]})"
else
"$op()"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment