Groovy - Unit Testing

The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods.

JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case.

Writing a Simple Junit Test Case

Let assume we have the following class defined in a an application class file −

class Example {
   static void main(String[] args) {
      Student mst = new Student(); = "Joe";
      mst.ID = 1;
public class Student {
   String name;
   int ID;
   String Display() {
      return name +ID;

The output of the above program is given below.


And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code −

  • The test case class extends the GroovyTestCase class
  • We are using the assert statement to ensure that the Display method returns the right string.
class StudentTest extends GroovyTestCase {
   void testDisplay() {
      def stud = new Student(name : 'Joe', ID : '1')
      def expected = 'Joe1'
      assertToString(stud.Display(), expected)

The Groovy Test Suite

Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code −

  • The GroovyTestSuite is used to encapsulate all test cases into one.

  • In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing.

import groovy.util.GroovyTestSuite 
import junit.framework.Test 
import junit.textui.TestRunner 

class AllTests { 
   static Test suite() { 
      def allTests = new GroovyTestSuite() 
      return allTests