为什么Spock的交互不适用于由其他类构建的Mock

时间:2017-07-21 04:13:08

标签: unit-testing groovy spock

我正在尝试在一个类中组装所有Mock构建方法。 但是当我在其他groovy类上使用通过构建方法构建的Mock对象时。 Mock的存根似乎工作正常,但交互检查不起作用。 好吧......我应该怎么做到这一点?

MockTestingSpec.groovy

class MockTestingSpec extends Specification{

    def "use mock from other class"(){
        setup:"construct mock builder"
        def bldr = new MockBuilder()

        when:"build mock by MockBuilder"
        def mockObj = bldr.buildMock()

        and:"build mock by private method of this class"
        def builtAtThisClass = buildMock()

        then:"check stubbing are working. these conditions were satisfied"
        mockObj.getKey().equals("keyyyy")
        mockObj.getValue() == 12345
        builtAtThisClass.getKey().equals("keyyyy")
        builtAtThisClass.getValue() == 12345

        when:"put a mock to private method"
        callMockGetter(builtAtThisClass)

        then:"call each getter, these conditions were also satisfied"
        1 * builtAtThisClass.getKey()
        1 * builtAtThisClass.getValue()

        when:"puta a mock that built by builder"
        callMockGetter(mockObj)

        then:"these conditions were NOT satisfied... why?"
        1 * mockObj.getKey()
        1 * mockObj.getValue()
    }
    // completely same method on MockBuilder.
    private buildMock(String key = "keyyyy",Integer value = 12345){
        TestObject obj = Mock()
        obj.getKey() >> key
        obj.getValue() >> value
        return obj
    }

    private callMockGetter(TestObject obj){
        obj.getKey()
        obj.getValue()
    }
}

MockBuilder.groovy

class MockBuilder extends Specification{

    public buildMock(String key = "keyyyy",Integer value = 12345){
        TestObject obj = Mock()
        obj.getKey() >> key
        obj.getValue() >> value
        return obj
    }

    public static class TestObject{
        private String key
        public String getKey(){
            return key
        }
        private Integer value
        public Integer getValue(){
            return value
        }
    }
}

1 个答案:

答案 0 :(得分:1)

将模拟创建移动到超类是有效的。这样,您可以在多个规范中重用复杂的模拟创建。

abstract class MockCreatingSpec extends Specification {
    createComplexMockInSuperClass() {
        return Mock()
    }
}
class MockTestingSpec extends MockCreatingSpec {
    def "use mock from superclass"() {
        given:
        def mock = createComplexMockInSuperClass()
        ...
    }
}