使用 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)
注意:已省略了导入,以关注手动的问题
您无法做到这一点,因为控制器不是模拟的对象。相反,您需要使用这样的元素:
@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
}
}