【问题标题】:Grails integration test - Writing test to check, how many times a function is called in service classGrails 集成测试 - 编写测试以检查服务类中调用函数的次数
【发布时间】:2014-09-25 12:28:02
【问题描述】:

我有一个服务方法,它又从它调用另一个方法,多次。

定义方法A(){

.... 方法B() ....

}

有没有办法编写集成测试,可以测试“methodB()”被调用的次数?

使用单元测试可以完成,但可以集成完成吗?

【问题讨论】:

  • 是的。我正在使用 spock

标签: grails


【解决方案1】:

这是一个常规的 JUnit 3 测试,但该方法在 Spock 测试中可以正常工作。

您可以使用&. 运算符来获取对方法的引用并通过引用调用该方法,所以我会这样做,然后将元类中的方法替换为递增计数器的闭包,然后调用使用保存的参考的真实方法。

class FooServiceTests extends GroovyTestCase {

    def fooService

    void testCountMethodB() {

        def methodB = fooService.&methodB

        int count = 0
        fooService.metaClass.methodB = { ->
            count++
            methodB()
        }

        fooService.methodA()
        assert count == 5 // or whatever number you expect
    }
}

如果methodB 有参数,请务必注册一个具有相同签名的闭包,例如

fooService.metaClass.methodB = { int bar, String wahoo ->
   count++
   methodB(bar, wahoo)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    相关资源
    最近更新 更多