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;
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

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s