Thursday, April 12, 2012

Unit Test Grails Domain Class having a Relational Mapping

Let's say that we have two domain classes Book.groovy and Library.groovy.
//Book.groovy
package com.example.book

class Book {
static constraint = {
name blank: false, size: 2..255, unique: true
}
static belongsTo = [lib: Library]
String name
}

//Library.groovy
package com.example.library

class Library {
static hasMany = [book: Book, branch: Branch]
static constraints = {
name blank: false
place blank: false
}
String name
String place
}

To unit test Book class you need to create an object of Library class since Book 'belongsTo' library with a back reference.

So our unit test will be:
//BookUnitTests.groovy
package com.example.book

import grails.test.*
import com.example.library.*

class BookUnitTests extends GrailsUnitTestCase {

def b //book
def lib //library

protected void setUp() {
super.setUp()
lib = new Library(name: "My Library", place: "XYZ Ave")
mockForConstraintsTests(Book)
}

protected void tearDown() {
super.tearDown()
}

void testPass() {
b = new Book(name: "MyBook", lib: lib) //pass the Library object to which the book belongs to.
assert b.validate()
}
}