【发布时间】:2017-02-18 23:48:13
【问题描述】:
当静态类在其他 Java 类中使用时,Groovy 测试不会为静态类创建模拟。下面是证明这一点的代码sn-p
被测Java类:
public class JavaClass {
public void method() {
ClassWithStaticMethod.doSomething();
}
}
带有静态方法的Java类:
public class ClassWithStaticMethod {
public static void doSomething() {
System.out.println("Static method called");
}
}
Groovy 测试失败:
class JavaClassTest extends Specification {
def 'test'() {
given:
GroovyMock(ClassWithStaticMethod, global: true)
JavaClass javaClass = new JavaClass()
when:
javaClass.method()
then:
1 * ClassWithStaticMethod.doSomething() // <--- FAILS
}
}
这会失败并显示消息:
Static method called <--- original method is called, it's not mocked
Too few invocations for:
1 * ClassWithStaticMethod.doSomething() (0 invocations)
Unmatched invocations (ordered by similarity):
None
因此,不会模拟静态方法,而是始终调用实际的实现。谁能解释这种行为?知道如何绕过这个吗?
Java 版本:1.7.0_79,Groovy 版本:2.4.7,Spock 版本:1.0-groovy-2.4,cgclib:3.1
【问题讨论】:
标签: java unit-testing groovy mocking spock