Unit testing Groovy每实例元类方法重写不';在Spock测试中未按预期工作
我有一个方法为execute()的类。在一些Spock单元测试中,我模拟了execute方法,并给它一个模拟闭包,如下所示:Unit testing Groovy每实例元类方法重写不';在Spock测试中未按预期工作,unit-testing,groovy,spock,stub,Unit Testing,Groovy,Spock,Stub,我有一个方法为execute()的类。在一些Spock单元测试中,我模拟了execute方法,并给它一个模拟闭包,如下所示: def setup () { rule = new DynamicRule () } def "test default execution " (){ given : "basic AORule " def mockres rule.metaClass.execute = {-> mockres = "did nothing"}
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"
}
如果我运行此测试,它将失败。在idea编辑器中,它将模拟闭包显示为带下划线的,但下一行的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的闭包
此测试的修改版本成功运行:
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的一个公开问题,这里:
用元类重写私有方法时有一个错误。如果我用
rule=new Object()
而不是new DynamicRule()
(因为你没有提供它),来执行你的测试,它会起作用吗?我想DynamicRule有一个名为execute
的私有方法?哈,这就解释了-我还以为我很笨,很高兴知道一些弹珠留在了旧的坦克-谢谢-我有一个解决办法(可能更好)使用的存根,所以我在这里好了now@WILLIAMWOODMAN如果这个答案对你有帮助,不要犹豫接受它;-)