15.1 Unit Testing

Unit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without consideration for surrounding infrastructure. Unit tests are typically run without the presence of physical resources that involve I/O such databases, socket connections or files. This is to ensure they run as quick as possible since quick feedback is important.

Since Grails 3.3, the Grails Testing Support Framework is used for all unit tests. This support provides a set of traits. An example hello world test can be seen below:

  1. import spock.lang.Specification
  2. import grails.testing.web.controllers.ControllerUnitTest
  3. class HelloControllerTests extends Specification implements ControllerUnitTest<HelloController> {
  4. void "Test message action"() {
  5. when:"The message action is invoked"
  6. controller.message()
  7. then:"Hello is returned"
  8. response.text == 'Hello'
  9. }
  10. }

For more information on writing tests with Grails Testing Support see the dedicated documentation.

Versions of Grails below 3.2 used the Grails Test Mixin Framework which was based on the @TestMixin AST transformation. This library has been superceded by the simpler and more IDE friendly trait based implementation. However you can still use it by adding the following dependency to your Grails application:

build.gradle

  1. testCompile "org.grails:grails-test-mixins:3.3.0.RC1"

This may be useful if you are, for example, upgrading an existing application to Grails 3.3.x.