Spock - 如何检查 Spy 对象上的方法调用计数?

MFI*_*san 2 unit-testing spock

我很难让这个斑点测试发挥作用。

我有一个 Spring repo/DAO 类,它多次调用存储过程。我正在尝试编写一个单元测试来验证 SP 是否被调用“x”次(3 次调用 createSP() 方法)。

public class PlanConditionRepositoryImpl{

    ....

    public void write() {
        for (int i=0; i<3; i++) {
            createSP(new ConditionGroup(), new Condition()).call();
        }
    }

    protected StoredProcedure<Void> createSP(ConditionGroup planConditionGroup, Condition planCondition) {
        return new StoredProcedure<Void>()
                .jdbcTemplate(getJdbcTemplate())
                .schemaName(SCHEMA_NAME);
    }
}       
Run Code Online (Sandbox Code Playgroud)

然而,下面的实现并没有这样做。如何实现调用计数检查?或者如何避免调用createSP()方法的实际实现。

def write(){
    def repo = Spy(PlanConditionRepositoryImpl){
        createSP(_, _) >> Spy(StoredProcedure){
            call() >> {
                //do nothing
            }
        }
    }
    when:
    repo.write()

    then:
    3 * repo.createSP(_, _)
}
Run Code Online (Sandbox Code Playgroud)

这就是我使用 hack 解决它的方法。但是有没有一种解决方案可以使用 Spock 的基于交互的测试而不引入额外的变量呢?

def "spec"() {
    given:
    def count = 0
    def spy = Spy(PlanConditionRepositoryImpl){
        createSP(_, _) >> {count++}
    }

    when:
    spy.write()

    then:
    count == 3
}
Run Code Online (Sandbox Code Playgroud)

Opa*_*pal 5

您需要的是部分模拟,请查看文档。然而,正如我所说,部分模拟基本上是不好的做法,并且可能表明设计不好:

(使用此功能之前请三思。更改规范下的代码设计可能会更好。)

关于部分嘲笑:

// this is now the object under specification, not a collaborator
def persister = Spy(MessagePersister) {
  // stub a call on the same object
  isPersistable(_) >> true
}

when:
persister.receive("msg")

then:
// demand a call on the same object
1 * persister.persist("msg")
Run Code Online (Sandbox Code Playgroud)

以下是测试的编写方式:

@Grab('org.spockframework:spock-core:1.0-groovy-2.4')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class Test extends Specification {
    def "spec"() {
        given:    
        def mock = Mock(StoredProcedure)
        def spy = Spy(PlanConditionRepositoryImpl) 

        when:
        spy.write()

        then:
        3 * spy.createSP() >> mock
        3 * mock.run()
    }
}

class PlanConditionRepositoryImpl {

    void write() {
        for (int i = 0; i < 3; i++) {
            createSP().run()
        }
    }

    StoredProcedure createSP() {
        new StoredProcedure()    
    }
}

class StoredProcedure {
    def run() {}
}
Run Code Online (Sandbox Code Playgroud)