如何测试是否使用Spock从Grails 3中的另一个实例方法中调用实例方法

时间:2017-04-26 18:52:49

标签: spock grails3

使用 Grails 3.2.8 Spock 框架进行测试,给出以下控制器类:

class SomeController {
    def doSomething() {
        // do a few things, then:
        someOtherMethod()
    }

    protected void someOtherMethod() {
        // do something here, but I don't care
    }
}

如何测试 doSomething()方法以确保只调用someOtherMethod()一次?

这是我失败的尝试:

@TestFor(SomeController)
class SomeControllerSpec extends Specification {
    void "Test that someOtherMethod() is called once inside doSomething()"() {
        when:
        controller.doSomething()

        then:
        1 * controller.someOtherMethod(_)
    } 
}

错误讯息:

Too few invocations for:

1 * controller.someOtherMethod(_)   (0 invocations)

注意:已省略导入以关注手头的问题

1 个答案:

答案 0 :(得分:0)

由于控制器不是模拟对象,因此无法做到这一点。相反,你需要使用这样的元类:

@TestFor(SomeController)
class SomeControllerSpec extends Specification {
    void "Test that someOtherMethod() is called once inside doSomething()"() {
        given:
            Integer callsToSomeOtherMethod = 0
            controller.metaClass.someOtherMethod = {
                callsToSomeOtherMethod++
            }
        when:
            controller.doSomething()

        then:
            callsToSomeOtherMethod == 1
    } 
}