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.

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

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:

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

class BookUnitTests extends GrailsUnitTestCase {

def b //book
def lib //library

protected void setUp() {
lib = new Library(name: "My Library", place: "XYZ Ave")

protected void tearDown() {

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