unit-testing - Grails/Spock : How to mock single method within class where method is called from within the class itself?

标签 unit-testing grails groovy spock

鉴于以下内容,我如何使用 Spock 模拟 processMessage(),以便我可以检查 processBulkMessage() 调用 processMessage() n 次,其中 n 是 BulkMessage 中的消息数?

class BulkMessage {
    List messages
}

class MyService {

    def processBulkMessage(BulkMessage msg) {
        msg.messages.each {subMsg->
            processMessage(subMsg)
        }
    }

    def processMessage(Message message) {

    }
}

最佳答案

您可以使用 spies和部分模拟(需要 Spock 0.7 或更新版本)。

After creating a spy, you can listen in on the conversation between the caller and the real object underlying the spy:


def subscriber = Spy(SubscriberImpl, constructorArgs: ["Fred"])
subscriber.receive(_) >> "ok"

Sometimes, it is desirable to both execute some code and delegate to the real method:


subscriber.receive(_) >> { String message -> callRealMethod(); message.size() > 3 ? "ok" : "fail" }

关于unit-testing - Grails/Spock : How to mock single method within class where method is called from within the class itself?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27446102/

相关文章:

php - 测试期间在 Laravel 中重置数据库中的记录,而不是数据库本身

grails - Grails:如何为集合检索持久值?

java - Groovy 中用于 Java 类的动态字段

spring - 找不到使用域类资源创建的Grails REST API返回

java - Java 类中的 Groovy 特性

c++ - 第一个 CppUnit 测试:对 CppUnit::SourceLine::SourceLine 的 undefined reference

java - Camel : Mock a processor to test Route

java - Mockito 使用参数模拟新实例调用

performance - 为什么Grails推荐使用 Action 作为方法的 Controller 的单例作用域?

Grails 3 PluginDescriptor 配置