groovy / grails / unit testing / createCriteria.get

不羁岁月 提交于 2019-12-03 06:14:29

I've found a solution that doesn't compromise my ability to write unit tests -

def myCriteria = new Expando();
myCriteria .get = {Closure  cls -> returnThisObject}         
MyDomainClass.metaClass.static.createCriteria = {myCriteria }

which does exactly what I wanted and potentially supports testing supplied arguments. Thanks for the other response. Hope this is useful to others testing domain/createCriteria() methods.

I wouldn't bother. Instead create methods in your domain class and mock those. This makes testing easier but more importantly has the advantage of keeping persistence where it belongs instead of scattering it throughout the code base:

class MyDomainClass {
   String foo
   int bar

   static MyDomainClass findAllByIdAndAnotherParameter(long id, long anotherParameterId) {
      createCriteria().list {
         eq('id',id)
         eq('anotherParameter',anotherParameterId)
      }
   }

   static MyDomainClass getByIdAndAnotherParameter(long id, long anotherParameterId) {
      createCriteria().get {
         eq('id',id)
         eq('anotherParameter',anotherParameterId)
      }
   }
}

Then in your tests, just mock it as

def testInstances = [...]
MyDomainClass.metaClass.static.findAllByIdAndAnotherParameter = { long id, long id2 ->
   return testInstances
}

and

def testInstance = new MyDomainClass(...)
MyDomainClass.metaClass.static.getByIdAndAnotherParameter = { long id, long id2 ->
   return testInstance
}

This should be much simpler now with the GrailsUnitTestCase.mockDomain1 method.

grails-app/domain/sandbox/grails/foo/Something.groovy

package sandbox.grails.foo

class Something {
    String name
}

test/unit/sandbox/grails/foo/SomethingTests.groovy

package sandbox.grails.foo

import grails.test.mixin.*
import org.junit.*

@TestFor(Something)
class SomethingTests {

    void testSomething() {

        mockDomain(Something, [
            new Something(name: 'Foo'),
            new Something(name: 'Bar'),
            new Something(name: 'Boo'),
            new Something(name: 'Baz')
        ])

        def actuals = Something.createCriteria().list(sort: 'name', order: 'asc') {
            like('name', '%oo')
        }

        assertEquals 2, actuals.size()

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!