Initializations in Grails Unit Test Cases

14 / Jun / 2011 by Imran Mir 4 comments

Most of us have experienced how important the Unit test cases are for our code base. I feel the other thing that is equally important, is the speed at which we can write the unit test cases. In Unit Testing, initializing different objects in setup of the test case (e.g., while testing a method which queries the database) can become a pain, especially when the objects to be initialized have many attributes and relationships. Grails/Spock have simplified initialization process for us. All we need to is to initialize just the required attributes of the objects, along with the id field,e.g., while testing a method of a class Student :

class Student {
  String name
  String fathersName
  String address
  static belongsTo = [school: School]

 static constraints = {
    name(nullable: false)
    fathersName(nullable: false)
    address(nullable: false)

  List<Student> findMySchoolsStudentsWithNamesLike(String nameLike) {
    List<Student> students = Student.findAllBySchoolAndNameLike(, '%' + nameLike + '%')
    return students


To test the method, a Spock test case with the simplified initializations will be like:

 def "My School students are retrieved correctly"() {
    School school = new School(id: 1)
    List<Student> students = (1..10).collect {new Student(id: it, name: "name${it}", school: school)}
    mockDomain(Student, students)

    students[0].findMySchoolsStudentsWithNamesLike('1').size() == 2

Similar setup can work in Grail Unit test case.
Simplification of the initialization process has made Unit testing simpler and faster, thus allowing us to write more Unit test cases.

Imran Mir


comments (4)

  1. Massage therapy in stafford

    Great beat ! massage would like to apprentice at the same time as you amend your website, how could massage subscribe for a weblog website? The account aided me a acceptable deal. massage have been tiny bit acquainted of this your broadcast provided shiny transparent idea

  2. vippi

    Pikalaina 50 – 1000€ hae lainaa – Euroloan- VälimuistissaPikalainan tarpeeseen –palvelu tarjoaa täsmälainan, jossa voit itse määrittää laina-ajan ja … Pikalainan hakeminen on tehty helpoksi ja turvalliseksi.


Leave a comment -