Hi, is there a way to say "listA should contain on...
# kotest
k
Hi, is there a way to say "listA should contain only the elements a, b, c"? For example:
Copy code
listOf(1, 1, 1).shouldContainOnly(1) -- passes (if there was such a function as shouldContainOnly)
listOf(1, 1, 2, 2).shouldContainOnly(1, 2) -- passes
listOf(1, 1, 2).shouldContainOnly(1) -- fails
e
shouldContainExactly
although your 2nd example would fail, only
listOf(1, 1, 2, 2).shouldContainExactly(1, 1, 2, 2)
would pass.
k
The 1st example would fail too.
e
Copy code
listOf(1,1,2,2).forAll {
            it.shouldBeOneOf(1, 2)
         }
k
Thanks, Emil. I was looking for a succinctly named, single function equivalent to AssertJ's
containsOnly
function, but this will do.
e
If you'd like you could create an issue for it, I think it's likely to get accepted ­čÖé
k
Thanks, Issue 3213 created.
d
We have
shouldContainExactlyInAnyOrder
right?
k
listOf(1, 1, 1).shouldContainExactlyInAnyOrder(1)
fails.
In the absence of
shouldContainOnly
Kotest can be used only with workarounds, such as by making changes to the actual value to be tested. Compare AssertJ's
containsOnly
with attempts to use Kotest:
Copy code
package org.example

import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.collections.*
import org.junit.jupiter.api.Test
import org.assertj.core.api.Assertions.*

class KotlinPracticeTest {
    @Test
    fun foo() {
        // AssertJ's containsOnly method is what is required
        assertThat(listOf(1, 1, 1)).containsOnly(1)
        assertThat(listOf(1, 1, 2, 2)).containsOnly(1, 2)
        shouldThrow<AssertionError> { assertThat(listOf(1, 1, 2)).containsOnly(1, 2, 3) }

        // There is no Kotest method to do the same thing:
        // it only works with workarounds such as converting the actual value to be tested
        listOf(1, 1, 1).toSet().shouldContainExactlyInAnyOrder(1)
        listOf(1, 1, 2, 2).toSet().shouldContainExactlyInAnyOrder(1, 2)  //fails
        shouldThrow<AssertionError> { listOf(1, 1, 2).toSet().shouldContainExactlyInAnyOrder(1) }
    }
}
d
Ah yes, in that case we could use a generic
shouldMatchAll
kind of function that you can use with a predicate