willowtreeapps / assertk

assertions for kotlin inspired by assertj
MIT License
757 stars 84 forks source link

Feature Request: Add description to `matchesPredicate` assertion #514

Open jdsee opened 6 months ago

jdsee commented 6 months ago

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.

evant commented 6 months ago

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

jdsee commented 6 months ago

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? 😃

evant commented 6 months ago

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()
saket commented 6 months ago

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 commented 6 months ago

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

evant commented 6 months ago

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)

saket commented 6 months ago

Subscribed to #352!