Spock没有检测到方法调用

时间:2016-05-21 09:30:56

标签: unit-testing testing groovy spock

Spock未检测到 doTip 方法调用

(我需要分享一些"其中"阻止。)

使用最新 groovy spock

为什么这段代码错了?

如何解决?

import spock.lang.Shared
import spock.lang.Specification

class Test extends Specification {
def controller
@Shared
String g = ""
@Shared
def tip = Mock(Tip)

def "test"() {
    controller = new TController(tip: tip)
    when:
    controller.transform(g)

    then:
    1 * tip.doTip(_)
}
}

class Tip {
def doTip(String f) {}
}

class TController {
Tip tip

def transform(String g) {
    tip.doTip(g)
}
}

1 个答案:

答案 0 :(得分:2)

使用setup()创建模拟,如下所示:

@Grab(group='org.spockframework', module='spock-core', version='1.0-groovy-2.4')

import spock.lang.*

class Test extends Specification {
    def controller
    @Shared String g = ""
    @Shared tip

    def setup() {
        tip = Mock(Tip)
    }

    def "test"() {
        given:
        controller = new TController(tip: tip)

        when:
        controller.transform(g)

        then:
        1 * tip.doTip(_)
    }
}

class Tip {
    def doTip(String f) {}
}

class TController {
    Tip tip

    def transform(String g) {
        tip.doTip(g)
    }
}

结果

JUnit 4 Runner, Tests: 1, Failures: 0, Time: 78