Annyce Davis

Davis Technology Consulting

  • Home
  • About Me
  • Blog
  • Courses
  • Newsletter

Updated: Mocking Hibernate Create Criteria in Grails’ Unit Test with GMock

December 6, 2010 by Annyce Davis

Using the GMock Library I have updated my unit tests to mock out the create criteria methods the following way:

void testSomeFunction() {
def results = []

def mockCriteria = mock() {
list(instanceOf(Closure)).returns(results)
}

mock(Book).static.createCriteria().returns(mockCriteria)

play {
assertEquals null, bookService.getDefaultBook(null)
}
}

You need to add the following to the top of the unit test file with the import statements:

import org.gmock.*
import static org.hamcrest.Matchers.*

@WithGMock

Also add the following to your BuildConfig.groovy:

dependencies {
test "org.gmock:gmock:0.8.0"
test "org.hamcrest:hamcrest-all:1.0"
}

I learned this from the following blog post: http://adhockery.blogspot.com/2010/01/using-gmock-to-complement-grails.html

Using Grails’ mockParams with Associations

March 24, 2010 by Annyce Davis

If you have a class Book which contains a list of authors and would like to test this functionality in your Controller’s unit tests. This is how you would do it, using the Grails mockParams.

void testSaveOfBookWithAuthor() {
mockRequest.method = ‘POST’
mockParams.title = “Book Title”
mockParams[“authors”] = [[“author.id”:”123″, “author”:[“id”:”123″]]]
controller.save()
}

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!

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