【问题标题】:How to use assertThat with any condition?如何在任何条件下使用 assertThat?
【发布时间】:2021-08-19 18:34:45
【问题描述】:

我怎样才能写出下面的断言:

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

与 Google Truth assertThat?

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

【问题讨论】:

    标签: kotlin junit any google-truth assertthat


    【解决方案1】:

    如果我不熟悉 Google Truth(因此我不知道是否有惯用的方式来编写它),我会这样写这个断言:

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

    或者,您可以保留原始版本:

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

    玩一下,你甚至可以这样做:

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

    但是,后者看起来不太可读,所以我会坚持使用第一个。

    【讨论】:

    • @ChrisPovirk 感谢您更新答案并修复示例 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多