Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Groovy unit tests


May 14, 2021 Groovy


Table of contents


The basic unit of an object-oriented system is a class. T herefore, unit tests consist of tests in a class. b20> ds. owever, unit tests should be performed on key and critical methods.

JUnit is an open source testing framework that is a recognized industry standard for Java code automation unit testing. es. ll that is needed is to extend the Groovy TestCase class as part of the standard Groovy environment. T he Groovy test case class is based on junit test cases.

Write a simple Junit test case

Let's say we define the following classes in the application class file:

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

Lower than given in the output of the above program.

Joe1

Now suppose we want to write a test case for the Sent class. T ypical tests are shown below. The following points need to be noted in the following code -

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

Groovy test suite

Typically, as the number of unit tests increases, it becomes difficult to continue with all test cases one by one. Therefore, Groovy provides a tool for creating a test suite that encapsulates all test cases into a single logical unit. T he following snippppy code shows how this can be achieved. You should be aware of the following things in the code -

  • GroovyTestSuite is used to encapsulate all test cases.

  • In the following example, let's assume that we have two test case files, one called StudentTest and the other employeeTest, which contain all the necessary tests.

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

class AllTests { 
   static Test suite() { 
      def allTests = new GroovyTestSuite() 
      allTests.addTestSuite(StudentTest.class) 
      allTests.addTestSuite(EmployeeTest.class) 
      return allTests 
   } 
} 

TestRunner.run(AllTests.suite())