GroovySpy not working when static methods invoked from within closure (1.0-groovy-2.3)
Consider this class with some static methods:
class SomeClass {
public static String method1 () {
[1].each {
commonMethod()
}
}
public static String method2 () {
for (def i: [1]) {
commonMethod()
}
}
public static String commonMethod() {
}
}
method1 and method2 both call commonMethod but in different ways. method1 invokes commonMethod from a closure, while method2 invokes it from within a for loop.
Now consider the following spec:
class SomeClassSpec extends Specification {
// This fails
def "method1"() {
given:
def spy = GroovySpy(SomeClass, global:true)
when:
spy.method1()
then:
1 * SomeClass.commonMethod() >> "ASDF"
}
// This passes
def "method2"() {
given:
def spy = GroovySpy(SomeClass, global:true)
when:
spy.method2()
then:
1 * SomeClass.commonMethod() >> "ASDF"
}
}
I would expect both tests to pass, but the first one fails. In the first test, the real SomeClass.commonMethod is being invoked (not expected), while in the second test, it is not (expected).
I am having the same issue with a static method call from within a finally block.
try { Context context = ContextFactory.global.enterContext() ... } finally { Context.exit() }
The real Context.exit() method is always called. I'm going to write my method a bit different to make it testable, but just wanted to point out a similar issue I just ran into.
A colleague hit this issue and found a workaround by qualifying the call with the class name. I tested it myself with the below method and verified that the test passes:
public static String method1 () {
[1].each {
SomeClass.commonMethod()
}
}