When writing unit tests in Grails 3.x, we have to mock domains. Here is the example code.
package com.example.service
import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import spock.lang.Ignore
import spock.lang.Specification
@TestFor(SomeService)
@Mock([DomainA, DomainB])
class SomeServiceSpec extends Specification{
...
}
The problem is when a new domain is added, lets say DomainC and the unit tests are dependent upon DomainC, then those unit tests fails. We then have to manually have to add DomainC.
Is there a way to dynamically mock the domains?
@TestFor(SomeService)
@Mock([dynamically mock all domain objects here])
class SomeServiceSpec extends Specification{
...
}
Maybe this is what you need (from grails doc ).
Alternatively you can also use the DomainClassUnitTestMixin directly with the TestMixin annotation and then call the mockDomain method to mock domains during your test:
@TestFor(BookController)
@TestMixin(DomainClassUnitTestMixin)
class BookControllerSpec extends Specification {
void setupSpec() {
mockDomain(Book)
}
...
Also mockDomains
method exists for the list of domains, which you can retrieve by standard way from context.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.