google/truth

Asymmetric matchers like Jest's expect.stringContaining("") ?

samuelneff opened this issue · 3 comments

Is it possible to integrate an asymmetric matcher into Google Truth assertions, like in Jest?

It would look something like this:

val actual = listOf("abc", "def")
assertThat(actual).contains(stringContaining("d"))

Basically anything that checks equality would check if the expect side of the equation is an asymmetric matcher and if so use that for equality test.

So in this case, the assertion would pass since the list contains an element that is a string containing the letter d.

Looking through the source for IterableSubject::containsExactlyElementsIn for example seems to indicate this is not possible. It uses built-in Objects.equal(actual, expected) for the equality check.

If it reversed the check and was doing Objects.equal(expected, actual) then this could be done as the expected value is the one that would have custom comparisons implemented.

Yes, @kluever has it. It would be roughly:

assertThat(actual).comparingElementsUsing(stringContainment()).contains("d")

...where stringContainment() returns something like...

Correspondence.from(String::contains, "contains")

(Or you could just use that directly instead of defining a method.)

That is exactly what I was referring to, thank you!!! I didn't know Truth's terminology. 👍