groovy / grails / unit testing / createCriteria.get

后端 未结 3 1015
無奈伤痛
無奈伤痛 2021-02-08 11:20

I can mock calls to:

MyDomainClass.createCriteria().list{
    eq(\'id\',id)
    eq(\'anotherParameter\',anotherParameterId)
}

with:

<         


        
3条回答
  •  情话喂你
    2021-02-08 11:41

    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
    }
    

提交回复
热议问题