March 17, 2008

Groovy: no such property: X for class Y

Having taken up the task of learning Groovy, I stumbled early, as I tried to figure out how to integrate groovy-based unit tests with my java code. I had a java class called ContactScreen, and I wrote a groovy test case:

class ContactScreenTest extends GroovyTestCase {   
    void testStandardEmailScreen() {
       screen = ContactHelper.getStandardContactScreen( Contact.EMAIL )
       assertTrue( screen instanceof AnyDayEmailScreen )
    }
}

Which failed when I tried to run it via Eclipse, giving the following error:

testStandardEmailScreen(ContactScreenTest)groovy.lang.MissingPropertyException: No such property: screen for class: ContactScreenTest

I stared at that error for a long time, wondering what the heck it meant. I mean, I’ve seen all sorts of example groovy scripts that don’t require definitions. In fact, the code I was modeling mine after used this very format. What is going on?

Finally, I turned to the groovy user group to help debug my groovy test case. Here’s what I found:

  1. The code I was looking at, circa 2004, is now victim to a fairly significant shift in language specification. In other words, it won’t compile anymore.
  2. The rules for declaring variables is different for scripts versus classes. In other words, if you are just running a script, you don’t need to declare variables. If you are building a class, you have to declare the members of the class via def.

So the working code looks like this:

class ContactScreenTest extends GroovyTestCase {
 void testStandardEmailScreen() {
 	def screen = ContactHelper.getStandardContactScreen( Contact.EMAIL )
 	assertTrue( screen instanceof AnyDayEmailScreen )
 }
}