Annyce Davis

Davis Technology Consulting

  • Home
  • About Me
  • Blog
  • Courses
  • Newsletter

Mocking Hibernate Criteria in Grails App

January 14, 2010 by Annyce Davis

Testing is always a sore spot in many applications, and Grails is no exception, but mocking objects and methods is actually not as bad as you think. Here is a simple way to mock the Hibernate Criteria object that is available from Grails domain classes.

Example:
If this is the code that you want to test, and for this particular test you want to have no results, this how you would mock it out.

Code:

Test Code:

The key piece of code is the creation of the bookCriteria object, in this case it is a member of the test class that is why it is not declared locally in the function. However, you will notice that the bookCriteria is simply a HashMap that returns a empty list for the ‘list’ parameter. This way when testing ‘c.list’ a empty list will be returned. Simple hunh!

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on Bluesky (Opens in new window) Bluesky
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on Reddit (Opens in new window) Reddit

Related

Filed Under: Grails Tagged With: Groovy, Mock, Testing

Follow Me

  • Bluesky

Categories

  • Android (60)
  • Career (5)
  • Communication (4)
  • Flutter (1)
  • Git (4)
  • Gradle (4)
  • Grails (23)
  • iOS (1)
  • Java (8)
  • JavaScript (6)
  • Kotlin (17)
  • Life (5)
  • Public Speaking (26)
  • Revenue (2)
  • RxJava (1)
  • Software Development (13)
  • Twitter (3)
  • Uncategorized (11)
  • Video Course (5)

Follow Me

  • Bluesky

Copyright © 2025 · All Rights Reserved · Log in