How do I use executeQuery in grails testcase?
Question
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!
Solution
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 }
OTHER TIPS
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]}
In Grails 2.5.4 you can use GroovyMock
for mocking static methods implemented in Java:
GroovyMock(Book, global: true)
I just tested - it works also for _.executeQuery()