willowtreeapps / assertk

assertions for kotlin inspired by assertj
MIT License
760 stars 85 forks source link

How to do either-or assertions? #450

Open hakanai opened 1 year ago

hakanai commented 1 year ago

I have a value where it can either be null, or if non-null it must match a pattern.

So I'd like to be able to do something like

assertThat(value).any(
    { a -> a.isNull() },
    { a -> isNotNull().matches(Regex("""some pattern""")) }
)

The existing code I'm converting from Java and AssertJ is using anyOf(Condition...) to do this.

I guess matchesPredicate is possible as a last resort, but it removes all potential for reusing existing assertions. :(

evant commented 1 year ago

Could be a useful addition, but in the meantime I think you'd be best served with a custom assertion. More manual work but you could get a better message out of it.

hakanai commented 1 year ago

If it were just the one place in the tests using it, I'd probably hack up a custom assertion for that place, but there are several occurrences all with different rules for what options they accept.

I wish I could figure out how to extract a message from the inner assertions. I haven't looked at how all {} is doing it yet, but any is the direct counterpart to all so the two should probably work similarly.