tags:

views:

273

answers:

3

Hello, 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

+5  A: 

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.

Burt Beckwith
A: 

There's no mock implementation for Hibernate criteria at the present time. You'll need to use integration tests. However, Burt's recommendation of making this a static finder method is a good one for code organization. You should also look at named queries, described at http://www.grails.org/1.2+Release+Notes, for a nice syntax for this.

John Stoneham
+1  A: 

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.

Peter Ledbrook