keskiviikko 25. helmikuuta 2009

Improving Grails TDD within Eclipse

Grails 1.1 unit testing has support for mocking domain classes/objects. This feature is very nice.

These are additional instructions to the previous ones.

Additional instructions to run a Grails domain class unit test:
1. Copy the below code to a file called [grails app rootdir]/src/java/GrailsAwareGroovyTestSuite.java .
2. Update the Eclipse Run Configuration for the launcher created by the previously posted instructions.
3. Change the Test Class name to "GrailsAwareGroovyTestSuite".
(previous instructions contain the full procedure)

I've posted this to the Grails JIRA, it's GRAILS-4123.

UPDATE: Check the JIRA issue to get the latest version of this code.


import grails.util.BuildSettings;
import grails.util.BuildSettingsHolder;
import groovy.util.GroovyTestSuite;

import java.io.File;

import junit.framework.Test;

import org.codehaus.groovy.grails.compiler.injection.ClassInjector;
import org.codehaus.groovy.grails.compiler.injection.DefaultGrailsDomainClassInjector;
import org.codehaus.groovy.grails.compiler.injection.GrailsAwareClassLoader;
import org.codehaus.groovy.grails.compiler.support.GrailsResourceLoader;
import org.codehaus.groovy.grails.plugins.GrailsPluginUtils;

/**
*
* Adds support for running Grails JUnit Tests from Eclipse JUnit runner or even
* from the command line.
*
* Set GRAILS_HOME environment variable before running the test.
* Change the working directory to the Grails application's root directory.
*
*
* more information: http://quest4grail.blogspot.com/search/label/junit
*
*
* @author Lari Hotari
*
*/
public class GrailsAwareGroovyTestSuite extends GroovyTestSuite {
protected final GrailsAwareClassLoader gcl;

public GrailsAwareGroovyTestSuite() {
File basedirFile = new File(".").getAbsoluteFile();
System.setProperty(BuildSettings.APP_BASE_DIR, basedirFile.getPath());
BuildSettings grailsSettings = new BuildSettings(new File(System.getenv("GRAILS_HOME")), basedirFile);
BuildSettingsHolder.setSettings(grailsSettings);

gcl = new GrailsAwareClassLoader(getClass().getClassLoader());
gcl.setClassInjectors(new ClassInjector[] { new DefaultGrailsDomainClassInjector() });
gcl.setResourceLoader(new GrailsResourceLoader(GrailsPluginUtils.getArtefactResources(".")));
}

public static Test suite() {
GrailsAwareGroovyTestSuite suite = new GrailsAwareGroovyTestSuite();
try {
suite.loadTestSuite();
} catch (Exception e) {
throw new RuntimeException((new StringBuilder()).append("Could not create the test suite: ").append(e)
.toString(), e);
}
return suite;
}

@Override
public Class compile(String fileName) throws Exception {
return gcl.parseClass(new File(fileName));
}
}

1 kommentti: