implements Elegance {

// Elwyn Malethan's musings on software development, mountain biking and general navel–gazing...

Articles published in category Groovy

Groovy BeanFactory wrapper using propertyMissing

I‘ve been using Easyb for some integration style testing. The system I‘m testing has a bunch of dependencies all wired together using Spring. So my stories started getting filled up with non dynamic looking clunky Java just so I could get at my configured beans. Something like this:

import org.springframework.beans.factory.xml.XmlBeanFactory
import org.springframework.core.io.ClassPathResource

def beanFactory = new XmlBeanFactory(new ClassPathResource("storyContext.xml"))
def myService = beanFactory.getBean("myService")

scenario "Some integration test", {
  given "Some criteria", {
    // ...
  }
  when "my service is invoked", {
    service.turnLeadIntoGold()
  }
  then "I expect to see some results", {
    // ...
  }
}

For this one small example story it doesn‘t seem like a big deal. Most stories are far more elaborate however. Also add a few more stories and even the top few lines of this example starts looking very non–DRY. So my answer was this:

import org.springframework.beans.factory.xml.XmlBeanFactory
import org.springframework.core.io.ClassPathResource

class SpringHelper {

  private def beanFactory;

  def SpringHelper(String resource) {
    beanFactory = new XmlBeanFactory(new ClassPathResource(resource));
  }

  def propertyMissing(name) {
    beanFactory.getBean name
  }
}

Like a Ruby , Groovy supports dynamic methods and properties (Ruby doesn‘t distinguish between the two). This seems so simple, that it surprises me that I couldn‘t find it done already somewhere.

So now my stories are a little leaner and a little tidier.

import com.malethan.easyb.helpers.SpringHelper

def spring = new SpringHelper("storyContext.xml")

scenario "Some integration test", {
  given "Some criteria", {
    // ...
  }
  when "my service is invoked", {
    spring.myService.turnLeadIntoGold()
  }
  then "I expect to see some results", {
    // ...
  }
}

I‘m pretty new to Groovy, so I may have missed a trick. It‘s nice to be working with a more flexible language again though.

First published on Sep 2, 2009. Last updated on: Dec 29, 2009.

 
People I like
Other sites