views:

95

answers:

2

I can mock calls to:

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

with:

def myCriteria = [
    list : {Closure  cls -> returnThisObject}
]
MyDomainClass.metaClass.static.createCriteria = { myCriteria }

as advised at:

http://davistechyinfo.blogspot.com/2010/01/mocking-hibernate-criteria-in-grails.html

but for:

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

This approach fails - maybe because 'get' is a keyword in a way 'list' is not. Can anyone advise - being able to mock this in domain classes should be possible, without simply abandoning unit test coverage for methods that use createCriteria().get{}.

Suggestions much appreciated,

Alex

+1  A: 

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
}
Burt Beckwith
I've simplified this to the following:
Alex
String hello = "hello"def map = [get1:{Closure cls -> hello}, address:"somewhere"]print map.get1{}
Alex
String hello = "hello"def map = [get:{Closure cls -> hello}, address:"somewhere"]print map.get{}
Alex
The difference is that when the map key is 'get1' then printing map.get1{} prints "hello", but when the key is 'get' then null is returned. Maybe 'get' is a language conflict so i need an entirely different approach for mocking out createCriteria().get{}.
Alex
A: 

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.

Alex