Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails withCriteria testing

Tags:

grails

groovy

I'd like to test a "withCriteria" closure and am not sure how to go about it. I see how to mock out the withCriteria call, but not test the code within the closure. When running the test that executes the "withCriteria", I keep getting a MissingMethodException, even though the code runs fine under the normal flow of execution. Any ideas? Thanks! Steve

like image 375
ptsw Avatar asked May 24 '10 17:05

ptsw


2 Answers

I wouldn't go that route. Instead I'd move the query into the domain class as a static finder method and test it directly in an integration test with real data. Then you can easily mock the helper method when it's called in a controller or service test.

class YourDomainClass {

...
   static List<YourDomainClass> findFooBar() {
      YourDomainClass.withCriteria {
         ...
      }
   }
}

Then in a unit test:

def results = [instance1, instance2, instance3]
YourDomainClass.metaClass.static.findFooBar = { -> results }

This way you test that the query works against the in-memory database in an integration test but it's easy to mock it in unit tests.

like image 60
Burt Beckwith Avatar answered Oct 14 '22 18:10

Burt Beckwith


Further to Burt's answer, check out named queries as described here:

http://blog.springsource.com/2010/05/24/more-grails-1-3-features/

You can then mock the property/method access in your unit tests as described by Burt.

like image 37
Peter Ledbrook Avatar answered Oct 14 '22 18:10

Peter Ledbrook