How to test a Grails Service that utilizes a criteria query (with spock)?

こ雲淡風輕ζ 提交于 2019-11-30 06:59:33

You should not use unit tests to test persistence - you're just testing the mocking framework.

Instead, move the criteria query to an appropriately named method in the domain class and test it against a database with an integration test:

class Event {
   ...
   static Set<Event> findAllEventsByDay(Date date, int offset, int max) {
      ...
   }
}

class EventService {

   Set<Event> listEventsForDate(Date date, int offset, int max) {
      ...
      return Event.findAllEventsByDay(date, offset, max)
   }
}

If there's still value in having the service method as a wrapper (e.g. if it implements some business logic above and beyond the database query), it will now be easy to unit test since it's trivial to mock out the static domain class method call:

def events = [new Event(...), new Event(...), ...]
Event.metaClass.static.findAllEventsByDay = { Date d, int offset, int max -> events }

And that's appropriate since you're testing how the service uses the data it receives and assuming that the retrieval is covered in the integration tests.

Criteria queries are not supported in unit tests. From the mockDomain documentation:

[T]he plugin does not support the mocking of criteria or HQL queries. If you use either of those, simply mock the corresponding methods manually (for example with mockFor() ) or use an integration test with real data.

You'll have to make your test an integration test. You'll see that the exception goes away if you move the test from the test/unit folder to the test/integration folder.

There is some work being done on criteria support in unit tests, and if you're feeling adventurous, you can try it out today. See this mailing list discussion of the DatastoreUnitTestMixin.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!