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()
}
}

Uninstall Subclipse from STS

Subversive plugin for STS is much better than subclipse svn plugin. Install subversive, and then uninstall subclipse by going to STS Help->'About SpringSource Tool Suite'->'Installation Details'->'Installed Software' and remove the ones with 'id' containing org.tigris.
Next navigate to STS plugin directory from the command line and run the following commands:
$ ls |grep org.tigris.subversion|xargs rm -rf
01 May 2012 Update: After working with this plugin for around three weeks, I find it difficult to make directory changes. I find it difficult to use STS with subversive plugin. I agree that it has got more options than subclipse, but when it comes to daily operations like commit, rename, delete directories, branching, it is a big mess (at least for me). So I am back to subclipse.