是否可以在Groovy类中测试一个方法,以便类中的其他方法将使用模拟版本?

时间:2016-02-18 19:24:49

标签: unit-testing groovy spock

例如:

class CutService {

    String delegateToSelf(){
        aMethod()
    }

    String aMethod(){
        "real groovy value from CUT"
    }
}

我尝试了各种方法,包括:

@TestFor(CutService)
class CutServiceSpec extends Specification {

    def expectedValue = "expected value"

    void "test mocking CUT method using MockFor"() {
        given:
        MockFor mockCutService = new MockFor(CutService)
        mockCutService.ignore.aMethod {expectedValue}
        def cutServiceProxy = mockCutService.proxyDelegateInstance()

        when:
        String actualValue = null
        mockCutService.use {
            actualValue = cutServiceProxy.delegateToSelf()
        }

        then:
        expectedValue == actualValue
    }
}

给出了:

| Failure:  test mocking CUT method using MockFor(com...CutServiceSpec)
|  junit.framework.AssertionFailedError: No more calls to 'delegateToSelf' expected at this point. End of demands.
        at com...CutServiceSpec.test mocking CUT method using MockFor_closure4(CutServiceSpec.groovy:45)
at com...CutServiceSpec.test mocking CUT method using MockFor(CutServiceSpec.groovy:44)

1 个答案:

答案 0 :(得分:1)

使用metaClass似乎可以做我想要的事情:

void "test mocking CUT method using metaClass"() {
    given:
    service.metaClass.aMethod = { expectedValue }

    when:
    String actualValue = service.delegateToSelf()

    then:
    expectedValue == actualValue
}

此测试运行为绿色。