-
Notifications
You must be signed in to change notification settings - Fork 261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Predicate-accepting assertions #404
Comments
/cc @JakeWharton |
One could argue this has nothing to do with Kotlin as such a method could be beneficial to Java 8 consumers as well. But since // No "T" to use, Object and ? aren't usable.
public void containsAny(Predicate<T> predicate) { /* .. */ } Nor is there a way to do it yourself with a Kotlin extension method: // Again no "T" to use and Any or * aren't usable.
fun IterableSubject.containsAny(predicate: (T) -> Boolean) = /* .. */ The best you can do with Kotlin, though, is hanging the extension off of the iterable directly: fun <T> Iterable<T>.assertContainsAny(predicate: (T) -> Boolean) {
assertTrue(this.any(predicate))
// TODO better failure message
} yielding mapMarkers.assertContainsAny { it.data == myData } The absence of a type parameter limits the ability to create these style helpers directly on the subject. All that being said, there are some really handy Kotlin extensions that I use with Truth. My favorite is: inline fun <reified T> assertThrows(block: () -> Unit): ThrowableSubject {
try {
block()
} catch (e: Throwable) {
if (e is T) {
return assertThat(e)
} else {
throw e
}
}
throw AssertionError("Expected ${T::class.simpleName}")
} (source) which lets you do: assertThrows<IllegalArgumentException> {
FunSpec.builder("foo")
.addTypeVariable(TypeVariableName("T").reified())
.build()
}.hasMessageThat().isEqualTo("only type parameters of inline functions can be reified!") (source) |
I suppose the Java instance method and the Kotlin extension function could define their own assertThat(listOf("Hello", "World")).containsAny<Integer> { it % 2 == 0 } which is an unnecessary foot gun. |
This looks like a duplicate of #206? |
@JakeWharton Of course you are totally right that it would be a treat to have @PhilippWendler The issue you linked is in fact part of what I want to archieve. Thanks for the hint. |
You can check this great assertion library for Kotlin https://github.com/robstoll/atrium |
Are there any plans to add an extension for usage in Kotlin? There would be a lot of potential. I'm still quite new to Truth so I hope I did not miss sth but for example I currently use
Instead it would be great to have
Quite interesting for collections would also be
all
andnone
. And I think there will be more examples like that which would be very nice to have.The text was updated successfully, but these errors were encountered: