Search code examples
grailsspock

How do I mock this object with composite id in Grails 2.4.5?


import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode(includes = ['action', 'reason'])
class MyObject implements Serializable {
    String action
    String reason
    String description

    static mapping = {
        table name: "my_object"
        version false
        id composite: ["action", "reason"], generator: 'assigned'

        cache usage: "read-only"

        action column: "prog_action_c"
        reason column: "prog_reason_c"
        description column: "descr_c"
    }
}

I tried to this mock this object in my unit tests as below :

.....
def setup() {
..
    mockDomain(MyObject,[
          [
            action : 'ACT1',
            reason : 'REAS1',
            description : 'First reason'
          ],
          [
            action : 'ACT2',
            reason : 'REAS2',
            description : 'Second reason'
          ]
     ])

     def myObject = MyObject.first()

}
...

When I queried the object with findAll() or first() I get empty list or null

How should this object be mocked?


Solution

  • The short answer is we can not mock objects this way in grails 2.4.5 How we can mock is : defining a method to load those objects in your controller/service whatever class you are testing. Then Spy the class tested, and mock the method to return whatever you want as the domain object(s).