Saturday, May 30, 2009

Testing Groovy domain classes

If you are trying to test Grails domain class constraints by putting your unit test cases in the 'test/unit' directory, then your tests will fail because the domain objects will not have the 'valdate' method. This can be resolved in two ways:
  1. Place the test cases inside test/integration (which will slow things down)
  2. Use the method 'mockForConstraintsTests(Trail)' to create mock method in your domain class and continue writing your test cases in 'test/unit'

What follows is some example code around this finding.

I am working on a Groovy on Grails project for a website to help programmers keep up and refresh their skills.

I started with some domain classes and then moved on to write some unit tests. When we create a Grails project using
grails create-app
it creates several directories, one of which is a directory called 'test' for holding unit tests. This directory contains two directories, 'unit', and 'integration' for unit and integration tests respectively.

Now begins an interesting journey with writing unit tests in Groovy. I wanted to write tests for my domain classes. A simple domain class like the one I have below can contain only properties and constraints for those properties. This is what Trail.groovy looks like.

class Trail {
String shortName
String name
String description

def hasMany = [learningObjects:LearningObject]

static constraints = {
shortName(maxSize:6, blank:false)
name(maxSize:75, blank:false)
description(maxSize:2048, blank:false)

I wanted to start writing unit tests to test the constraints. When Grails creates a domain class, it injects several methods in it at runtime , one of which is a method called 'validate'. This method is called before the domain object is saved and it will return a false if the domain object has violated any constraints. So, I created a simple unit test to test the constraints of Trail.groovy

This is what my initial test case looked like.

import grails.test.*

class TrailTests extends GrailsUnitTestCase {

def trail

protected void setUp() {
trail = new Trail(shortName:'sname',
name:'Java 101',
description:'This is a basic Java course')

protected void tearDown() {

void testShortNameConstraints() {
trail.shortName = 'thisisaverylongname'
trail.shortName = ''

//... further methods not shown

When I ran my tests using
grails test-app

(See how well Grails integrated testing), I got a bunch of errors that told me that the 'validate' method was not found. If you enjoy looking at stack traces... feast your eyes:

Testcase: testShortNameConstraints took 0.159 sec
Caused an ERROR
No signature of method: Trail.validate() is applicable for argument types: () values: []
groovy.lang.MissingMethodException: No signature of method: Trail.validate() is applicable for argument types: () values: []
at TrailTests.testShortNameConstraints(TrailTests.groovy:20)
at _GrailsTest_groovy$_run_closure4.doCall(_GrailsTest_groovy:203)
at _GrailsTest_groovy$
at _GrailsTest_groovy$_run_closure2.doCall(_GrailsTest_groovy:147)
at _GrailsTest_groovy$_run_closure1_closure19.doCall(_GrailsTest_groovy:113)
at _GrailsTest_groovy$_run_closure1.doCall(_GrailsTest_groovy:96)
at TestApp$_run_closure1.doCall(TestApp.groovy:66)
at gant.Gant$_dispatch_closure4.doCall(Gant.groovy:324)
at gant.Gant$_dispatch_closure6.doCall(Gant.groovy:334)
at gant.Gant$_dispatch_closure6.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:344)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:334)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.processTargets(Gant.groovy:495)
at gant.Gant.processTargets(Gant.groovy:480)

After some Googling I realized that the 'validate' method is injected into domain objects by the Grails framework, and therefore it does not exist when we instantiate the domain object from test code. I later found that if a test is placed inside 'test/integration' then the test cases are created as the objects would have been created by the Grails framework. So the domain objects would have the 'validate' method. But I also read in another place (I cannot remember where), that if possible it is k better to mock these special methods instead of putting tests in the integration directory, since these tests take longer to instantiate and can slow down the overral running time. And I found in yet another place that there exists a method called 'mockForConstraintsTests(Trail)' which will inject the 'validate' method along with some other methods. So, I added this mock method to my setup after which I was able to run my tests successfully.

protected void setUp() {
trail = new Trail(shortName:'sname',
name:'Java 101',
description:'This is a basic Java course')

The rest of the class is the same.

So to summarize, if you are trying to test constraints in Grails domain classes, you have two options:
  1. Place the test cases inside test/integration (which will slow things down)
  2. Use the method 'mockForConstraintsTests(Trail)' to create mock method in your domain class and continue writing your test cases in 'test/unit'
I will post more such episodes of how Google helped me resolve issues I faced while developing :-)

Tuesday, May 26, 2009

Groovy on Grails

Grails is a web application framework build on top of well known languages, frameworks and libraries. It uses the Groovy programming language which gives it power because of it's dynamic nature. Under the hoods, Grails uses Spring framework(for MVC), Hibernate (for OR mapping), Quartz (for scheduling), Log4J (for logging), JUnit for unit testing, and Canoo Webtest for functional testing.

We already have a Gazillion frameworks, do we need Grails ?

Typically web development in Java is a very long and arduous process. When a web project is started, many configuration files have to be set up after which the project development begins. Even then we have to create domain objects, basic controller functionality, the model, stylesheets, views, and other aspects of business logic. Grails makes things easier by allowing us to do all of these things rapidly and in fewer lines of code. So how does Grails allow us to do all this with fewer lines of code? Grails uses convention over configuration.

If you have developed a JEE app with Struts, you probably remember configuring struts-config.xml to map ActionBeans, Actions, Action classes, Global forwards, and so on. A typical development workflow with Struts is as follows:

  1. Create struts-config
  2. Create ActionBean classes and write their validators
  3. Create Action classes and delegate persistence and other things to model classes
  4. Create a Hibernate configuration file
  5. Create views with JSP's using Taglibs
  6. Write unit tests (these two are not really the last two... remember TDD)
  7. Write functional tests

Whew.... isn't that a lot of work to do? In Java I have always felt like there is just a lot of coding and configuration that needs to be done to make even the smallest web application.

Grails takes away a lot of this pain. This means we do not have to specify and code the smallest of things if we follow certain conventions. We however have the ability to break the conventions if we want to (in case of integrating with legacy databases, etc) by adding configuration.

So, for example lets assume we want to make a simple application to manage a music collection. We start with creating a Grails app with a grails command, after which we create a domain class. Thats it. Grails will scaffold the application for us, meaning it will create the entire infrastructure to give basic CRUD functionality with our domain object (this includes the controller, and views for adding, deleting, updating, and modifying data). So within minutes we have something we can use. Off course in most situations we will not want something as simple as this. We will have to extend the application in various ways. But I suspect, even after extending the application we will still have saved some time by using Grails, and there is another benefit. Because Grails gives us something really quickly, we can use the Agile approach where we quick feedback on what we are trying to accomplish, and every feedback loop actually gives us something that is usable and .

Because Grails is written in Groovy which is a JVM language, we can take advantage of all the Java libraries that we have become familiar with and also gain benefits from the JVM's optimizations.

A few other features of Grails which I have noticed and like are:

  1. Ability to upgrade to a newer version of Grails with a single command
  2. Automated creating of test classes (thus prodding you to write unit tests)
  3. Ability to use different databases for testing, development and deployment
  4. Command for creating domain objects, and controllers
  5. Inbuilt UI templating
  6. Host of third party plugins that extend the Grails framework
  7. Extremely simple mechanism to create Tag libraries
These are some of the features that I have read about, but I am sure there are many more.

If you build web applications in Java, Grails is definitely be something you should look into.

More about Grails coming up in future posts.

Monday, May 18, 2009

Internet and new media for teaching and learning

Today, Freeman and I did a video talk for a faculty development program at SCIT on how teachers can use the Internet and New Media for teaching and learning.

Some useful links for those who are new to this medium.

Google Groups is a good and simple way to start a mailing list.

Google Reader is a good blog reader.

For hosting a blog, I recommend either Blogger or Wordpress to start with. If you want more control, you can download the Wordpress software and install it in your own server.

ITunes is a good client software for listening to podcasts. But ITunes works only on Windows and Mac. For those running Linux, the Miro Player is a good option for video podcasts, and Amarok or JPodder for audio podcasts.

ITunes university has several podcasts hosted by universities worldwide.

If you want to create a podcast, you can use Audacity for recording them and Odeo for free hosting.

Those interested in Twitter can head straight to and here is an article describing how Twitter was used by a professor in the classroom.

To host your bookmarks on the net, you can use Delicious.

Free wiki hosting is available at PBWiki. If you want to install your own wiki, then download Mediawiki, or Twiki.

Moodle is the course management system that we spoke about.

Some educators who have inspired me by sharing their knowledge are: Stephen Downes, Konrad Glogowski, and Leigh Blackall

Friday, May 15, 2009

CompSci videos at Stanford

I came across some very interesting videos published by Stanford. These videos are recordings of some computer science courses offered at Stanford. I still have not had a chance to see all of them, but I am sure they will be very informative.

  • Programming methodology series at Stanford (lectures 23/24 may be useful for developers who already know programming) - video
  • Programming abstractions series at Stanford (looks like an interesting lectures. They focus on data structures, implications of using certain data structures, recursion, algorithm analysis like the Big O notation) - video
  • Programming paradigms series at Stanford (Talks about imperative, OO, & functional programming. Also discusses many good low level things like pointers, big/little Endian, representation of data as bytes, and also touches on algorithms, assembly code, etc) - video
  • Machine learning series at Stanford - video
I hope you find these useful. I will share more links as I discover them.