assertk icon indicating copy to clipboard operation
assertk copied to clipboard

add containsOnce/containsAllOnce assertions

Open wjtk opened this issue 3 years ago • 6 comments
trafficstars

I think that would be helpful to add two assertions for Iterables: containsOnce(elem) - works as contains, but throws when elem occurs more than one time containsAllOnce(vararg elements) - as above, but for list of elems (like contains/containsAll) I've added first assertion in my project and I found it useful.

Wdyt? Can I try to make PR?

wjtk avatar Jan 01 '22 18:01 wjtk

I've made PR, can you review it, please?

wjtk avatar Apr 11 '22 15:04 wjtk

@evant @rf43 @nishtahir, please?

wjtk avatar Aug 25 '22 18:08 wjtk

Sorry for the late reply but I think the first usecase is now covered with

assertThat(list).single().isEqualTo(expected)

I'm a little confused by containsAllOnce(), what's the usecase of such a method?

evant avatar Dec 06 '23 20:12 evant

Hi @evant, I think you didn't see my PR. Let's start with example, there is list:

val list = listOf(1, 2, 3, 4, 1)

and my proposed assertions should work as:

assertThat(list).containsOnce(2) // ok
assertThat(list).containsOnce(1) // error, 1 is two times on the list

assertThat(list). containsAllOnce(2, 3, 4) // ok
assertThat(list). containsAllOnce(2, 3) // ok
assertThat(list).containsAllOnce(1, 2) // error because 1 is two times on the list

Is there any straightforward equivalent now?, WDYT?

PS. Maybe it could be just one method with vararg:

        val list = listOf(1, 2, 3, 4, 1)
        assertThat(list).containsOnlyOnce(2, 3, 4)
        assertThat(list).containsOnlyOnce(2)

wjtk avatar Dec 11 '23 21:12 wjtk

Right, I'm curious what you'd use that for. It may be just me but it seem tricky to think about what matches and what doesn't.

evant avatar Dec 11 '23 22:12 evant

I have a case that I need this. Sometimes is useful to check that element exists and is not duplicated on the list.

I checked assertj yesterday, and it has containsOnlyOnce assertion, so I think I'm not the only one, that would use it. I found usages of it in my company repos, even in kotlin projects.

wjtk avatar Dec 12 '23 08:12 wjtk