unit-testing - Groovy 每个实例元类方法重写在 Spock 测试中无法按预期工作

标签 unit-testing groovy spock stub

我有一个类,其方法称为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/

相关文章:

java - Java 中比较器的 JUnit 测试

ruby-on-rails - 如何测试使用系统命令的代码

groovy - 使用 opencsv 从 csv 文件中删除引号

grails - Spock 在接口(interface)中未显示的动态方法上抛出 MissingMethodException

java - 如何通过 Kotlin Gradle 和 -D 为我的测试提供系统属性

unit-testing - 单元测试中的 Grails Spock 模拟注入(inject)服务

python - 使用 Moto 进行 Pytest,使用后端更改 athena 查询的状态

带有@Input装饰器的Angular 6 Karma测试子类

hibernate - 如何动态修改 groovy hibernate 查询

java - 如何防止在对象数组中获取 Groovy boolean 值?