'Spock tests fail with NullPointerException once global GroovyMock was used polluting grails testing environment
I noticed sometimes my tests would fail after repeated runs. I realized that it happens once I use a GroovyMock([global:true], SomeClass). The mocked classes no longer work in other Specification classes.
Example where a global mock can be setup:
@TestFor(EmploymentService)
class EmploymentServiceSpec extends Specification {
Agreement agreement
Member member
def setup() {
agreement = GroovyMock([global: true], Agreement)
member = GroovyMock([global: true], Member)
}
def "some test"() {
...
}
Other class where you need the real thing:
@TestFor(OtherService)
class OtherServiceSpec extends Specification {
Agreement agreement
Member member
def setup() {
agreement = new Agreement()
member = new Member()
}
def "some test"() {
member.someMethod() // would throw NPE here
}
How can I turn off / clean up global mocks once I finished using them in a Specification?
Solution 1:[1]
Use @ConfineMetaClassChanges([Your, GloballyMocked, Classes]) on the method or class where you use global mocks to revert the global effect after usage.
More in ConfineMetaClassChanges documentation
Source:
One blog covered this, pointing to a GitHub discussion, where they pointed to using @ConfineMetaClassChanges([%%MOCKED_CLASS%%]).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ev0oD |
