有问题
我有一个名为execute()的类 . 在一些spock单元测试中,我假设了execute方法并给它一个这样的模拟闭包
def setup () {
rule = new DynamicRule ()
}
def "test default execution " (){
given : "basic AORule "
def mockres
rule.metaClass.execute = {-> mockres = "did nothing"} //mock the action
def res = rule.execute()
expect : "execute should do nothing "
mockres == "did nothing"
}
如果我运行此测试它失败 . 在构思编辑器中,它以下划线显示模拟闭包 . 但是下一行的rule.execute()不是 - 所以它可以看到方法
如果我改变这个测试
rule.metaClass.execute2 = {-> mockres = "did nothing"} //mock the action
def res = rule.execute2()
然后测试通过 .
在spock之外我只是运行了一个简单的groovy脚本,并且方法重载并且正常工作,因为id期望并且该方法被封闭模拟
class A {
def execute () {
println "thing"
}
}
def c = new A()
def res
c.execute()
c.metaClass.execute = {-> res =2 ; println "modified thing "; }
c.execute ()
println "res = "+ res
为什么在spock测试中不会发生同样的情况?
查询 - 单元存根如何正确测试spock的闭包?
此修改版本的测试成功运行
def "test default execution " (){
given : "basic AORule "
def mockres
def stub = new StubFor(AORule)
stub.demand.execute { mockres = "did nothing" }
// rule.metaClass.execute = {-> mockres = "did nothing"} //mock the action
// def res = rule.execute()
expect : "execute should do nothing "
stub.use {
rule.execute()
mockres == "did nothing"
}
}
为什么简单的每个元类frig在spock中工作?我在这里不理解的东西
1 回答
这是一个关于Groovy> = 2.4.3的问题,这里是:GROOVY-7368 .
使用元类覆盖私有方法时存在一个错误 .