Search code examples
kotlinjunitanygoogle-truthassertthat

How to use assertThat with any condition?


How can I write the following assertion:

org.junit.Assert.assertTrue(result.any { it.name == "Foo" })

with Google Truth assertThat?

com.google.common.truth.Truth.assertThat(result...

Solution

  • Provided that I'm not familiar with Google Truth (hence I don't know if there's an idiomatic way to write it), I would write that assertion like this:

    Truth.assertThat(result.map { it.name }).contains("foo")
    

    or, you can keep the original version:

    Truth.assertThat(result.any { it.name == "foo" }).isTrue()
    

    Playing a bit with it, you could even do:

    Truth.assertThat(result)
            .comparingElementsUsing(Correspondence.transforming<Foo, String>({ foo -> foo?.name }, "has the same name as"))
            .contains("foo")
    

    However, the latter doesn't look very readable, so I'd stick with the first one.