如何让 Groovy Spock 测试将调用参数与等于而不是 ==

问题描述 投票:0回答:1

我的 Spring 应用程序有这个 Groovy 测试。

given:
    def mapProperties = new JSONObject().put(
      "eligibility", "true").put(
      "group", "group1")
when:
    trackingService.sendUnifiedOnboardingAssignmentUserUpdate()
then:
    1 * trackingCollector.send(new UserUpdate(mapProperties))

Tracking Collector 是外部的,在我扩展的规范中定义为 Spring Bean。

@SpringBean
TrackingCollector trackingCollector = Mock()

trackingService
在我的域层中并且是自动连接的

测试应该成功运行,但没有。

Too few invocations for:

1 * trackingCollector.send(new UserUpdate(mapProperties))   (0 invocations)

Unmatched invocations (ordered by similarity):

1 * trackingCollector.send(UserUpdate(super=Event(properties={"group":"group1","eligibility":"true"})))
One or more arguments(s) didn't match:
0: argument == expected
   |        |  |
   |        |  UserUpdate(super=Event(properties={"group":"group1","eligibility":"true"})) (com.package.tracking.collector.UserUpdate@4fe5aac9)
   |        false
   UserUpdate(super=Event(properties={"group":"group1","eligibility":"true"})) (com.package.tracking.collector.UserUpdate@48bb5a69)

唯一不同的是

@....
。但为什么 Groovy 不检查对象的实际值而是选择比较对象呢?在这种情况下,我需要做什么才能使测试通过?

groovy spock lombok
1个回答
0
投票

Spock 使用 Groovy truth,所以它会简单地将这两个对象与

equals
进行比较,或者
compareTo
如果它们正在实现
Comparable
.

包含对象 id 的输出是一个误会,Spock 仅在两个对象具有相同的字符串渲染时将其包含在输出中,以便更容易找出问题所在。

如果您无法修复

equals
实现,您可以使用 code 参数约束 手动检查必要的值。

如评论中所述,您的问题源于这样一个事实,即 equals 方法未针对您的用例正确实施。

© www.soinside.com 2019 - 2024. All rights reserved.