Spock中抽象类或具体类的属性访问测试

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

[当我使用getter / setter对模拟抽象或具体类,然后访问该属性时,永远不会调用相应的getter / setter。但是,如果为接口创建了Mock,则此方法可以正常工作。在下面的代码中,有3组,每组两个测试(一个测试getter和另一个setter),除了它们的模拟之外,它们是相同的。第一组工作良好,因为它们正在接口上进行测试,但是后两组却不能:

import spock.lang.Specification

interface Foo {
    public String getProp();

    public void setProp(String val);
}

abstract class FooBase implements Foo {
    public abstract String getProp();

    public abstract void setProp(String val);
}

class FooImpl extends FooBase {
    public String getProp() {
        println('Foo.getProp')
        return null
    }

    public void setProp(String val) {
        println('Foo.setProp')
    }
}

class TestPropertyAccess extends Specification {
    def 'test setter on interface'() {
        given:
            def foo = Mock(Foo)

        when:
            foo.prop = 'val'

        then:
            1 * foo.setProp(_)
    }

    def 'test getter on interface'() {
        given:
            def foo = Mock(Foo)

        when:
            foo.prop

        then:
            1 * foo.getProp()
    }

    def 'test setter on abstract'() {
        given:
            def foo = Mock(FooBase)

        when:
            foo.prop = 'val'
            //foo.setProp('val')

        then:
            1 * foo.setProp(_)
            //1 * foo.setProperty('prop', 'val')
    }

    def 'test getter on abstract'() {
        given:
            def foo = Mock(FooBase)

        when:
            foo.prop
            //foo.getProp()

        then:
            1 * foo.getProp()
            //1 * foo.getProperty('prop')
    }

    def 'test setter on concrete'() {
        given:
            def foo = Mock(FooImpl)

        when:
            foo.prop = 'val'
            //foo.setProp('val')

        then:
            1 * foo.setProp(_)
            //1 * foo.setProperty('prop', 'val')
    }

    def 'test getter on concrete'() {
        given:
            def foo = Mock(FooImpl)

        when:
            foo.prop
            //foo.getProp()

        then:
            1 * foo.getProp()
            //1 * foo.getProperty('prop')

    }
}

如果将属性访问权限替换为相应的getter / setter或测试通用的getProperty / setProperty,则可以使失败的测试工作。

我是否缺少某些东西,或者这可能是spock错误?

groovy mocking spock
1个回答
0
投票

好!考虑到以下事实,我认为这是一个Spock错误:

  • 如果添加真实属性并设置设置器并通过getter获取,则从常规Groovy程序中调用时,相同的代码可使用点属性表示法。
  • 该测试在Spock 1.3和2.0预览中的行为有所不同(存在getter测试,只有setter测试失败)。>>
  • 可能在AST转换中变了样,在编译过程中从Spock DSL生成了实际代码。

    您将打开故障单还是应该?

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