https://kotlinlang.org logo
#strikt
Title
k

Klitos Kyriacou

07/19/2023, 2:13 PM
Does Strikt have a matcher for iterables similar to AssertK's
containsOnly
(or Kotest's
shouldContainOnly
)? Description from AssertK: "Asserts the iterable contains only the expected elements, in any order. Duplicate values in the expected and actual are ignored."
j

Jakub Gwóźdź

07/19/2023, 3:08 PM
containsExactlyInAnyOrder
(I don’t know how it treats duplicates, so
.toSet()
before matching might be required)
k

Klitos Kyriacou

07/19/2023, 3:15 PM
Thanks. The treatment of duplicates is different, so as you suggest, the equivalent of AssertK's
Copy code
assertThat(listOf(0,0,0)).containsOnly(0)
is
Copy code
expectThat(listOf(0,0,0).toSet()).containsExactlyInAnyOrder(0)
which is a bit more cumbersome.
c

christophsturm

07/19/2023, 5:17 PM
you can just extract your own containsOnly matcher
ok in that case you cannot just extract it but it could look like this:
Copy code
fun <T : Iterable<E>, E> Assertion.Builder<T>.containsOnly(vararg elements: E): Assertion.Builder<T> =
    assert("contains only $elements") {
        if (it.toSet() == elements.toSet()) pass() else fail()
    }
💡 1
2 Views