【问题标题】:Groovy per instance metaClass method override doesn't work as expected in Spock testGroovy per instance metaClass 方法覆盖在 Spock 测试中无法按预期工作
【发布时间】:2016-06-12 22:54:36
【问题描述】:

我有一个类,其方法名为 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 中不起作用?

【问题讨论】:

  • 如果我使用rule = new Object() 而不是new DynamicRule() 执行您的测试(因为您没有提供),它可以工作吗?
  • 我想 DynamicRule 有一个名为 execute 的私有方法?

标签: unit-testing groovy spock stub


【解决方案1】:

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

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

【讨论】:

  • 哈哈,这解释了-我以为我很笨,很高兴知道旧水箱里还剩下一些弹珠-谢谢-我有一个使用存根的解决方法(可能更好),所以我好的,现在就到这里
  • @WILLIAMWOODMAN 如果这个答案对你有帮助,请不要犹豫接受它;-)
猜你喜欢
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多