If I check if all elements of a list are equal to ...
# kotest
k
If I check if all elements of a list are equal to a certain value:
Copy code
listOf(0, 0, 1).forAll { it shouldBe 0 }
the failure message says that one element fails:
Copy code
2 elements passed but expected 3

The following elements passed:
0
0

The following elements failed:
1 => expected:<0> but was:<1>
Is it possible to make it tell me which element failed (it was element at index 2 in the above case)?
c
```The following elements passed:
0
0
The following elements failed:
1 ```
As you can see, the first two passed, and the third one failed. I'm not sure what more information you want?
k
Something like:
Copy code
The following elements failed:
1 (at index 2)
For comparison with other libraries:
Copy code
Strikt: expectThat(listOf(0, 0, 1)).all { this isEqualTo 0 }
▼ Expect that [0, 0, 1]:
  ✗ all elements match:
    ▼ 0:
      ✓ is equal to 0
    ▼ 0:
      ✓ is equal to 0
    ▼ 1:
      ✗ is equal to 0
              found 1


AssertK: assertThat(listOf(0, 0, 1)).each { it.isEqualTo(0) }
expected [[2]]:<[0]> but was:<[1]> ([0, 0, 1])
s
Looking at the source, I believe what you want is `souldContainOnly`:
Copy code
kotlin
listOf(0, 0, 0).shouldContainOnly(0) // passes
listOf(0, 0, 0) shouldContainOnly listOf(0) // passes
listOf(0, 0, 0) shouldContainOnly listOf(0, 0) // passes
listOf(0, 0, 0) shouldContainOnly listOf(0, 1) // fails with "Some elements were missing: [1]"
listOf(0, 0, 0, 1, 2) shouldContainOnly listOf(0, 1) // fails with "Some elements were unexpected: [2]"
alternatively, there is also: -
shouldContainExactly
, for requiring that it contains the given values in the exact order. -
shouldContainExactlyInAnyOrder
, for requiring it contains the given values in any order. -
shouldContainAll
, for requiring that it contains at least one of all the values specified. -
shouldContainDuplicates
, for ensuring that it contains duplicates You can also check out CollectionMatchersTest (https://github.com/kotest/kotest/blob/master/kotest-assertions/kotest-assertions-core/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/collections/CollectionMatchersTest.kt) for examples of more collection matchers
k
Thanks,
shouldContainOnly
is more succinct than my previous usage of
forAll
, but it still doesn't tell you at which index it had found a non-matching element.
s
I guess if you really wanted the index, you could do something like this:
Copy code
kotlin
listOf(0, 0, 0).forEachIndexed { index, it ->
    withClue("index $index") {
        it shouldBe 0
    }
}
then, the clue will show the index when it fails. However, this may end up being kind of messy.
e
thank you color 1
231 Views