(Quick Reference)

12 Unit Testing

Version: 2024.0.0-M1

12 Unit Testing

To write unit tests with MongoDB and Spock you can simply extend from grails.test.mongodb.MongoSpec.

MongoSpec is an abstract class that will initialise GORM in the setup phase of the specification being executed. It uses by default a MongoClient instance that connects to a MongoDB instance as defined in your configuration (by default, localhost and port 27017, see [gettingStarted] for more details):

It is preferable to use testcontainers to automatically run MongoDB in a containerized environment and not have to run a MongoDB instance locally. The following examples use testcontainers:

Unresolved directive in <stdin> - include::./examples/grace-mongodb/src/test/groovy/functional/tests/EmbeddedMongoClient.groovy[]
Unresolved directive in <stdin> - include::./examples/grace-mongodb/src/test/groovy/functional/tests/LocalMongoUnitSpec.groovy[tags=structure]

You can also use your own low-level MongoClient instance, as shown in the following example:

Unresolved directive in <stdin> - include::./examples/grace-mongodb/src/test/groovy/functional/tests/BookUnitSpec.groovy[]

Note that the default implementation is to scan your classpath searching for domain classes, from the package defined in the configuration property grails.codegen.defaultPackage, and all the way down its subpackages. If your application is large, classpath scanning may be slow, so it’s better to override the method getDomainClasses():

Unresolved directive in <stdin> - include::./examples/grace-hibernate5-mongodb/src/test/groovy/functional/tests/BookFongoSpec.groovy[tags=getDomainClasses,indent=0]