Is it possible to create a Groovy package that can be used in a script without compilation?

Viewed 5940

I'm using groovy as a stand-alone scripting language (not compiling it) and am struggling with how to structure multiple files with the package keyword but still be able to import them in other files. An example of this would be the following:

Directory structure:

+-- Project
    +-- Example.groovy
    +-- ExampleTest.groovy

With the current setup, without any package keywords I can have the following:

// Example.groovy
class Example {
    String message

    def Example(input = "placeholder") {
        this.message = input
    }
}

//ExampleTest.groovy
import Example

class ExampleTest extends GroovyTestCase {
    void testInitialiserWithoutArg() {
        def object = new Example()
        assertEquals(object.message, "placeholder")
    }

    void testInitialiserWithArg() {
        def object = new Example("test")
        assertEquals(object.message, "test")
    }
}

With this, I can add a script in the project directory to use the example class or run the tests on the commandline with groovy ExampleTest.groovy (groovy bin is in PATH).

How do I then go about putting the Example class into a package so that a script can import the example class and I can run the unit tests on commandline? eg:

+-- Project
    +-- some
    |   +-- random
    |       +-- main
    |       |   +-- Example.groovy
    |       +-- test
    |           +-- ExampleTest.groovy
    +-- UseExample.groovy

I added package some.random to both Example.groovy and ExampleTest.groovy but even with Example.groovy and ExampleTest.groovy just in the /Project/some/random directory, I can't seem to work out how to import the Example class in ExampleTest.groovy to run the tests from the commandline or how to import the whole some.random package in a separate script like UseExample.groovy.

Is this possible or do I have to compile the package before I can use it?

2 Answers
Related