Search code examples
groovyspocklombok

How do I make Groovy Spock test compare invocation parameters with equals rather than ==


I have this Groovy test for my Spring application.

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

Tracking Collector is external and defined as a Spring Bean in the Specification I am extending.

@SpringBean
TrackingCollector trackingCollector = Mock()

trackingService is in my domain layer and is Autowired

The test should run successfully, but it's not.

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)

The only different thing is the @..... But why is Groovy not checking the actual value of the object and chooses to compare the objects instead? What do I need to do to make the test pass in this case?


Solution

  • Spock uses Groovy truth, so it will simply compare those two objects with equals, or compareTo if they are implementing Comparable.

    That the output contains the object id is a red-herring, Spock only includes it in the output when two objects have the same string rendering, to make it easier to figure out what is wrong.

    If you can't fix the equals implementation, you could use a code argument constraint to manually check for the necessary values.

    As noted in the comments your problems stems from the fact, that the equals method is not properly implemented for your use-case.