我为我的Spring应用程序准备了这个Groovy测试。
given:
def mapProperties = new JSONObject().put(
"eligibility", "true").put(
"group", "group1")
when:
trackingService.sendUnifiedOnboardingAssignmentUserUpdate()
then:
1 * trackingCollector.send(new UserUpdate(mapProperties))
跟踪收集器是外部的,在我正在扩展的规范中定义为Spring Bean。
@SpringBean
TrackingCollector trackingCollector = Mock()
trackingService
在我的域层并且是Autowired
测试应该运行成功,但是它没有。
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不检查对象的实际值,而是选择比较对象呢?在这种情况下,我需要做些什么才能使测试通过?
Spock使用Groovy的true,因此它将简单地将这两个对象与equals
进行比较,如果它们实现了Comparable
,则将其与compareTo
进行比较。
输出包含对象id是为了转移注意力,Spock只有在两个对象具有相同的字符串呈现时才会在输出中包含它,以便更容易找出问题所在。
如果你不能修复equals
的实现,你可以使用一个代码参数约束来手动检查必要的值。
正如在注释中所指出的,你的问题源于这样一个事实,即equals方法没有正确地为你的用例实现。