Automatic testing in Groovy from command line

If you have a need to do some automatic testing from the command line, Groovy can be of much help. Here’s a quick way to set this up. First, make sure you have both Groovy and Ant installed and the respective libraries in your PATH or CLASSPATH. For example, if you don’t have Ant installed, you can get exceptions such as:

Caught: java.lang.NoClassDefFoundError: org/apache/tools/ant/DemuxInputStream
  at groovy.util.FileNameFinder.class$(FileNameFinder.groovy)
  at groovy.util.FileNameFinder.$get$$class$groovy$util$AntBuilder(FileNameFinder.groovy)
  at groovy.util.FileNameFinder.getFileNames(FileNameFinder.groovy:37)
  at groovy.util.FileNameFinder.getFileNames(FileNameFinder.groovy:29)

Provided you have the above set up properly, here’s how you can make a simple test suite:

// Save this as AllTests.groovy
def ats = new groovy.util.AllTestSuite()
def suite = ats.suite("test", "**/*Test.groovy")
junit.textui.TestRunner.run(suite)

The above makes the AllTestsSuite, tells it to search the tests in “test” folder and also tells it to only consider files that match “*Test.groovy” (e.g. OneTest.groovy, MyCalculatorTest.groovy, etc.). Now, let’s make the test folder and put two sample tests in it:

// Save this to test/OneTest.groovy
class OneTest extends groovy.util.GroovyTestCase {
  void testOne1() {
    println("testOne1")
    assert 1 == 1
  }
  void testOne2() {
    println("testOne2")
    assert 1 == 1
  }
}

// Save this to test/TwoTest.groovy
class TwoTest extends groovy.util.GroovyTestCase {
  void testTwo1() {
    println("testTwo1")
    assert 1 == 1
  }
  void testTwo2() {
    println("testTwo2")
    assert 1 == 1
  }
}

If you now run this:

$ groovy AllTests.groovy

it should run all your tests and print something like this:

.testOne1
.testOne2
.testTwo1
.testTwo2

Time: 0.012

OK (4 tests)

Note that it’s not usual to use println in your tests – the above is just to make it obvious that the test suite we made executes all the tests. A good thing about this solution is that you don’t need to update the list of tests. If you want to make another test case, just make another file (e.g. LottoWinnerTest.groovy) and put it in test folder. AllTestSuite will find it automatically. Also, if you ever need to remove some of your tests, simply move them from test folder to some other location. All is very DRY.