assertk icon indicating copy to clipboard operation
assertk copied to clipboard

Feature Request: Add description to `matchesPredicate` assertion

Open jdsee opened this issue 1 year ago • 7 comments

Hi 👋

It would be great if the matchesPredicate assertion would allow a description parameter to be displayed on an assertion error instead of satisfy the predicate.

It could look something like this:

assertThat(x).matchesPredicate("some very special requirements") { it.isSpecial() }

which would then result in the error message:

expected X(special=false) to satisfy some very special requirements

I'm happy to submit a PR for this as soon as I find time for it.

jdsee avatar Feb 11 '24 13:02 jdsee

this already exists no? https://github.com/willowtreeapps/assertk/blob/main/assertk/src/commonMain/kotlin/assertk/assertions/predicate.kt

evant avatar Feb 12 '24 17:02 evant

Yes, the predicate matcher already exists. My request is to accept an optional description to improve the currently hardcoded error message.

Or am I still missing something? 😃

jdsee avatar Feb 12 '24 18:02 jdsee

Ah gotcha, I'm a little hesitant to add assertion-specific message overriding. There is some limited ability to override the message, for example you could set the name so that:

assertThat(12, name = "divisible by 5").matchesPredicate { it % 5 }

would give you

org.opentest4j.AssertionFailedError: divisible by 5
    expected 12 to satisfy the predicate

otherwise, I would really recommend using a custom assertion, where you can set the message exactly how you want

fun Assert<X>.isSpecial() = given { actual ->
    if (!it.isSpecial()) expected("${actual} to satisfy some very special requirements")
}

assertThat(x).isSpecial()

evant avatar Feb 13 '24 01:02 evant

I'm migrating my project to assertk and I have the same feature request. How do I replace my Truth.assertWithMessage() calls? I was using them as a way to describe my assertions. Here's an example:

https://github.com/saket/telephoto/blob/bdff7e6b09fb3a9785a3b54e0455e6fab6108539/zoomable-image/core/src/androidTest/kotlin/me/saket/telephoto/zoomable/ZoomableImageTest.kt#L610-L612

Using custom assertions to include messages feels a bit odd.

saket avatar Feb 16 '24 05:02 saket

Perhaps I can use Assert.all(message) as a stop-gap?

saket avatar Feb 16 '24 05:02 saket

yeah if something is going to be added it would be more general like assertWithMessage(), there's been a bit of discussion on adding to/customizing the error message but nothing's been settled on. (see https://github.com/willowtreeapps/assertk/discussions/352)

evant avatar Feb 16 '24 06:02 evant

Subscribed to #352!

saket avatar Feb 16 '24 06:02 saket