每个实例的metaClass方法重写无法在Spock测试中正常工作

问题描述 投票:2回答:1

我有一个方法叫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脚本,并执行了方法重载,并且可以按我期望的那样正常工作,并且该方法已使用闭包模拟了

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"

    }
}

为什么简单的每个元类在Spock中都不起作用?

unit-testing groovy spock stub
1个回答
2
投票

这是Groovy上的一个未解决的问题> = 2.4.3,在这里:GROOVY-7368

使用元类覆盖私有方法时存在一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.