Embracing the Messiness in Search of Epic Solutions

Java: Programmatically Compile and Unit Test Generated Groovy Source Code



My previous post shows how you can programmatically compile and unit test the generated Java source code. In this example, we will programmatically compile and unit test the generated Groovy source code.

Let’s assume we have the following service class that generates Groovy source code as one big String:-

public class GroovyCodeGeneratorService {
    public String generate(String packageName, String className) {
        return "package " + packageName +
               "\nclass " + className + " {" +
               "\n    boolean isOne(Integer i) {" +
               "\n      return i == 1" +
               "\n    }" +

To unit test the generated Groovy code, it is much simpler than Java:-

package com.choonchernlim.epicapp;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class GroovyCodeGeneratorServiceTest {

    GroovyCodeGeneratorService groovyCodeGeneratorService = new GroovyCodeGeneratorService();

    public void testGeneratedCode() throws Exception {
        String packageName = "com.choonchernlim.epicapp.service.impl";
        String className = "HelloWorld";

        String groovySource = groovyCodeGeneratorService.generate(packageName, className);

        ClassLoader parent = getClass().getClassLoader();
        GroovyClassLoader loader = new GroovyClassLoader(parent);

        Class groovyClass = loader.parseClass(groovySource);

        assertThat(invokeMethod(groovyClass, 1), is(true));
        assertThat(invokeMethod(groovyClass, 2), is(false));
        assertThat(invokeMethod(groovyClass, 0), is(false));
        assertThat(invokeMethod(groovyClass, -1), is(false));

    private boolean invokeMethod(Class groovyClass, Integer input) throws Exception {
        GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
        return (Boolean) groovyObject.invokeMethod("isOne", input);



Leave a Reply