-
Notifications
You must be signed in to change notification settings - Fork 41
Unit Test Support
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:
- grails doesn't cascading save on one-to-one relationships (
Face.build()
will create but won't save Nose): http://jira.grails.org/browse/GRAILS-8590 - fixed in grails 2.0.1 - grails saving a many-to-many will cause a stack overflow, will only affect BTD if your validation sets a minSize on a many-to-many relationship - http://jira.grails.org/browse/GRAILS-8747 - fixed in grails 2.0.1
- running tests in grails interactive mode doesn't clean up the metaclass - http://jira.grails.org/browse/GRAILS-8748 - fixed in grails 2.0.1