Search code examples
unit-testinggrailsgrails-ormspockgrails-3.0

How to populate domain classes in Grails 3 for unit tests


I was wondering as to how to build up a world of Domain class objects to use in my unit tests. What´s the best approach?

Say this is my code, ServiceX:

   List<Course> getAllCoursesByType(String type) {
        List<Course> list = Course.findAllByType(type)
        list
   }

This is the test for ServiceX:

 import grails.buildtestdata.mixin.Build
 import grails.test.mixin.TestFor
 import grails.test.mixin.Mock
 import spock.lang.Specification


  @TestFor(ServiceX)

    class ServiceXSpec extends Specification { 

      void "get all open courses"() {
       given:
       String type = "open"
       when:
       def list = service.getAllCoursesByType(type)

       then:
      list.size() == 4
     }

}

How can I "pre populate" the test-db (memory) sow that I actually have 4 such objects in the list?


Solution

  • It turns out you can add / override methods to the domain classes (for example), something like this:

    import grails.buildtestdata.mixin.Build
    import grails.test.mixin.TestFor
    import grails.test.mixin.Mock
    import spock.lang.Specification
    import grails.test.mixin.Mock
    
    
    @Mock([Course])
    @TestFor(ServiceX)
    
    class ServiceXSpec extends Specification { 
    
      void "get all open courses"() {
       given:
       String type = "open"
    
       Course.metaclass.static.findAllByType = { String type -> [new Course()]}
       when:
       def list = service.getAllCoursesByType(type)
    
       then:
       list.size() == 1
     }
    

    }