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

rocketraman

11/30/2020, 7:20 PM
Just checking out Strikt. My previous preferred library was hamkrest. My first assertion is to validate the count of elements in a list. I see
exactly
,
atMost
, and
atLeast
, but all of these take an additional predicate. Is the preferred approach to do this?
Copy code
expectThat(it).get { count() }.isEqualTo(3)
Is there any particular reason that there isn't a count matcher directly on list?
r

robfletcher

11/30/2020, 7:21 PM
expectThat(it).hasSize(3)
should work for you
r

rocketraman

11/30/2020, 7:52 PM
Its actually an
Iterable
, not a
List
. No
hasSize
matcher seems to be available.
r

robfletcher

11/30/2020, 7:59 PM
Okay, that’s because
Iterable
doesn’t define a
size
property. That’s added on
Collection
. It wouldn’t make sense for all iterables (they can be unbounded, for example). For your case
expectThat(it.toList()).hasSize(3)
is probably the way to go.
I mean, Strikt could add a
hasSize
for
Assertion.Builder<Iterable<*>>
but like I say it would not necessarily even make sense for every iterable
r

rocketraman

11/30/2020, 8:09 PM
The Kotlin stdlib does have a
count
function on
Iterable
. Normally unbounded iterables are represented as a
Sequence
.
r

robfletcher

11/30/2020, 8:14 PM
hmm, I could easily move
hasSize
up to work on Iterable I guess
r

rocketraman

11/30/2020, 8:16 PM
I think that makes sense, based on the extensions available in stdlib. Want me to create a GH issue?
r

robfletcher

11/30/2020, 8:16 PM
but it might make more sense to add a
count()
function so you could do
expectThat(it).count().isEqualTo(3)
to make it clear what the underlying API mapping is
r

rocketraman

11/30/2020, 8:17 PM
Makes sense to me
Out of curiosity, why does
hasSize
exist? Couldn't it work the same way?
Oh because List has a `size`property
r

robfletcher

11/30/2020, 8:20 PM
yeah, well…
Collection
does
which is what
count()
delegates to if called on a
Collection
otherwise it iterates over all the elements
r

rocketraman

11/30/2020, 8:21 PM
Yup
r

robfletcher

11/30/2020, 8:21 PM
I think the Strikt function would just be
Copy code
fun Builder<out Iterable<*>>.count(): Builder<Int> =
  get(Iterable<*>::count)
👍 1
r

rocketraman

12/02/2020, 7:09 AM
I can confirm that worked. I was going to submit a PR but I see you beat me to it with a release of 0.28.1. 🙌
👍 2
2 Views