What's the best way to write a custom matcher for ...
# kotest
k
What's the best way to write a custom matcher for a composite type? I think this should be added to the docs. For example
Copy code
data class Person(name: String, address: String)

fun aPerson(name: String, address: String): Matcher<Person> =
  object: Matcher<Person> {
    override fun test(value: Person): MatcherResult {
      if (value.name != name) {
        return MatcherResult(false, { "${value.name} should be $name" }, { "${value.name} should not be $name" })
      }

      if (value.address != address) {
        return MatcherResult(false, { "${value.address} should be $address" }, { "${value.address} should not be $address" })
      }

      return MatcherResult(true, { "person is correct" }, { "person is not correct" })
    }
  }
Is there a better way that I'm missing?
s
You could tidy it up by using a when rather than if's, but that looks ok to me
👍 1
k
Thanks @sam
p
@kierans777 as a possible improvement: you could accept from outside not only exact strings but matches. This way you’ll: 1. reuse existing matchers 2. make more flexible
aPerson
matcher that for instance could accept a matcher that would compare not only for exact equality but that either of fields might contain some sub string or check length of the field, etc.
👍 1
s
It should be possible to add some matcher combinators to Kotest too. So you can do Matcher.compose(nameMatcher, addressMatcher) kinda thing.
plus1 2
k
As I do a lot more FP with Arrow I'd love to compose matchers together. I wrote my own little setup that takes a list of functions, and returns the first failed
MatcherResult
or a success.
s
I would welcome a pr :)