【问题标题】:AssertJ and Groovy force type?AssertJ 和 Groovy 强制类型?
【发布时间】:2018-06-29 04:18:50
【问题描述】:

我在开发这个项目时正在学习 Groovy,所以我不确定自己的基础。

我有这样的断言:

assertThat( spyCH.getLoopCount() ).isEqualTo( 1 )

没有显式方法getLoopCount(),但CH类中有一个实例变量loopCount。 Groovy 会自动创建 getter 和 setter。

我声明了 CH 实例变量 loopCount 就像这样

def loopCount // i.e. "type undefined" (as yet)

实际上这达到了 11 的值。我得到了以下失败:

org.junit.ComparisonFailure: expected:<1[]> but was:<1[1]>

显然,结果被解释为字符串。然后我将实例变量更改为

int loopCount

...但我仍然得到相同的字符串比较

然后我将测试行改为:

assertThat( (int)spyCH.getLoopCount() ).isEqualTo( (int)1 )

...但我仍然得到相同的失败线。

有没有人知道如何强制 AssertJ 在 Groovy 中进行 int/Integer 比较? (注意它们在 Groovy 中是相同的:它没有原始值)。

【问题讨论】:

    标签: groovy types assertj


    【解决方案1】:

    JUnit 比较失败仅显示 表示String 的值之间的差异,但 isEqualTo 断言根据它们的类型比较值,最终执行类似 actual.equals(expected)(或 @987654325 @)。

    如果您执行assertThat( spyCH.getLoopCount() ).isEqualTo( 456 ),错误将如下所示:

    org.junit.ComparisonFailure: expected:<[1]> but was:<[456]>
    

    再次显示文本差异,但不将值作为字符串进行比较。

    在编写 assertThat(value) 时,java(我相信还有 Groovy)将使用最匹配的 assertThat 方法,如果 value 被声明或推断为 int,它将使用 assertThat(int actual),如果类型是未指定则选择assertThat(Object actual)

    希望能澄清一点

    【讨论】:

    • 是的,它澄清了这一点。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2014-05-02
    • 2019-07-16
    • 1970-01-01
    • 2021-01-24
    • 2011-07-17
    相关资源
    最近更新 更多