我有一个类,其方法称为execute()。在一些 Spock 单元测试中,我虚拟出执行方法并给它一个模拟闭包,如下所示:
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 脚本并执行了方法重载,并且它按照我的预期正常工作,并且该方法通过闭包进行了模拟
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 测试中没有出现同样的情况?
单元 stub 如何正确测试 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"
}
}
为什么简单的元类在 Spock 中不起作用?
最佳答案
这是 Groovy >= 2.4.3 上的一个未决问题,此处:GROOVY-7368 .
使用元类重写私有(private)方法时存在错误。
关于unit-testing - Groovy 每个实例元类方法重写在 Spock 测试中无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707386/