Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use executeQuery in grails testcase?

How do I use executeQuery in grails testcase?

A error : groovy.lang.MissingMethodException: No signature of method ***.executeQuery() is applicable for argument types: () values: []

I have already called mockDomain.

By the way, it is in unit test.

Thanks!

like image 449
LiCheng Avatar asked Feb 17 '12 07:02

LiCheng


2 Answers

There's no support for HQL queries in unit tests yet, but we're working on it. But you shouldn't be doing persistence tests with mocks. Persistence tests should be done against a database in an integration test.

I usually move HQL queries to the domain class as static query methods. This way they're easy to mock in a unit test of a controller, service, etc. and then I test the method as part of the domain class integration test.

For example I'd have

class User {
   String username
   String password
   ...

   static List findAllUsersBlahBlah(String foo, boolean bar) {
      executeQuery('from User u where ...')
   }
}

Then in a unit test I can mock that method with fake data since I don't care about persistence in a controller unit test - I know that it's properly tested in the correct place and I want to focus on the class under test, not its collaborators:

def users = [new User(...), new User(...)]
User.metaClass.static.findAllUsersBlahBlah = { String foo, boolean bar -> users }
like image 197
Burt Beckwith Avatar answered Sep 30 '22 18:09

Burt Beckwith


We have successfully mocked executeQuery with Grails 2.0 in our project

@TestFor(BookController)
@TestMixin([DomainClassUnitTestMixin,ServiceUnitTestMixin])
@ConfineMetaClassChanges([Book])
class BookControllerSpec extends Specification{
   mockDomain(Book)
   Book.metaClass.static.executeQuery = {a,b,c-> return [Book]}
like image 27
Ben W Avatar answered Sep 30 '22 19:09

Ben W