(Quick Reference)

8 Unit Testing - Reference Documentation

Authors: Graeme Rocher, Burt Beckwith

Version: 5.0.8.RELEASE

8 Unit Testing

For many simple cases you can use the built in GORM unit testing provided by Grails.

For more complex cases a grails.test.mixin.mongodb.MongoDbTestMixin class is provided which can run tests against a running MongoDB instance or a mock instance (such as one provided by the Fongo project).

Example against a running MongoDB instance:

import org.bson.types.ObjectId

@Entity class Person { ObjectId id Long version String name }

...

import grails.test.mixin.mongodb.*

@TestMixin(MongoDbTestMixin) class PersonSpec extends Specification{

void "Test count people"() { given:"A mongo domain model" mongoDomain([Person])

expect:"Count the number of people" Person.count() == 0 } }

Example using Fongo:

import com.github.fakemongo.Fongo
import grails.test.mixin.mongodb.*

@TestMixin(MongoDbTestMixin) class PersonSpec extends Specification{

void "Test count people"() { given:"A mongo domain model" Fongo fongo = new Fongo("mongo server 1"); mongoDomain(fongo.mongo, [Person])

expect:"Count the number of people" Person.count() == 0 } }

This library dependency is required in build.gradle for adding support for MongoDbTestMixin.

dependencies {
        test 'org.grails:grails-datastore-test-support:5.0.0'
    }

Fongo dependency example

dependencies {
        test 'com.github.fakemongo:fongo:1.5.4'
    }

Configuring domain classes for MongoDbTestMixin tests with the Domain annotation

The grails.test.mixin.gorm.Domain annotation is used to configure the list of domain classes that gets configured when the unit test runtime is initialized.

Domain annotations will be collected from several locations:

  • the annotations on the test class
  • the package annotations in the package-info.java/package-info.groovy file in the package of the test class
  • each super class of the test class and their respective package annotations
  • the possible api:grails.test.runtime.SharedRuntime class

Domain annotations can be shared by adding them as package annotations to package-info.java/package-info.groovy files or by adding them to a api:grails.test.runtime.SharedRuntime class which has been added for the test.

It's not possible to use DomainClassUnitTestMixin's Mock annotation in MongoDbTestMixin tests. Use the Domain annotation in the place of Mock in MongoDbTestMixin tests.

Example:

import grails.test.mixin.TestMixin
import grails.test.mixin.gorm.Domain
import spock.lang.Specification

@Domain(Person) @TestMixin(MongoDbTestMixin) class DomainAnnotationSpec extends Specification{ void "should allow registering domains with Domain annotation"() { given: def person = new Person(name:'John Doe') def personId = person.save(flush:true, failOnError:true)?.id expect:"Dynamic finders to work" Person.count() > 0 Person.get(personId).name == 'John Doe' } }