遇到问题
我有一个名为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中工作?我不理解的东西