0

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

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)

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

4

1 回答 1

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
    } 
}
于 2017-05-04T09:49:24.370 回答