Skip to content

Unit Test Support

Aaron edited this page Oct 27, 2015 · 1 revision

As of Grails 2.0, build-test-data can build() domain objects in unit tests.

To use it, you simply annotate your class with the @Build annotation (which supersedes the @Mock(Domain) annotation):

    import grails.buildtestdata.mixin.Build

    @Build(Author)
    class AuthorUnitTests {

        void testAuthorStuff() {
            def author = Author.build()
        ...

You can also pass in multiple domain object names to the annotation if desired (with multiple classes you'll likely also need to call mock on them in the same test):

    @Mock([Author, Publisher, Role])
    @Build([Author, Publisher, Role])

The plugin will analyze the constraints of the class(es) that you pass to the annotation. It looks at the object's constraints and will automatically decorate the class with grails GORM methods and a build() method. It will also walk the object graph for any non-nullable constraints and mock out related objects (so where a Book belongsTo and Author doing @Build(Book) will mock out both domain classes.

Alternatively, build-test-data has a BuildTestDataUnitTestMixin that you can pass to the @TestMixin annotation if you want to control when things are getting mocked out:

    import grails.buildtestdata.mixin.BuildTestDataUnitTestMixin
    import grails.test.mixin.TestMixin

    @TestMixin(BuildTestDataUnitTestMixin)
    class MixinAnnotationTests {

        void testMockForBuildAddsBuildMethod() {
            assert !Author.metaClass.hasMetaMethod('build')
            mockForBuild Author
            assert Author.metaClass.hasMetaMethod('build')

            def domainObject = Author.build()
            assert domainObject
        }
    }

There are a few issues in Grails 2.0.0 with scenarios that affect BTD but that Grails needs to fix in the 2.0.1 release:

Clone this wiki locally