【问题标题】:Grails: Mocking a service and its method inside another serviceGrails:在另一个服务中模拟一个服务及其方法
【发布时间】:2014-09-22 21:12:44
【问题描述】:

我有以下服务:

class MyMainService {

    def anotherService;

    def method1("data") {
         def response = anotherService.send("data")
    }

}

anotherService 是在 grails resources.groovy 中定义的一个 bean

我想通过模拟 anotherService.send("data")

对 MyMainService 中的 method1 进行单元测试

如何模拟 anotherService bean 及其 send() 方法的返回值并注入到我的 MyMainServiceSpec 测试类中? p>

我正在使用 grails 2.3.8。

谢谢。

【问题讨论】:

    标签: unit-testing grails grails-2.0 grails-services


    【解决方案1】:

    您可以使用 grails 中内置的默认模拟框架或选择使用 Spock 框架模拟样式。我更喜欢 Spock 框架,但选择权在你。以下是如何使用您的单元规范中可用的 grails mockFor 方法的示例。

    使用默认的 grails 模拟测试 MyMainService。

    @TestFor(MyMainService)
    class MyMainServiceSpec extends Specification {
    
        @Unroll("method1(String) where String = #pData")
        def "method1(String)"() {
            given: "a mocked anotherService"
            def expectedResponse = [:]  // put in whatever you expect the response object to be
    
            def mockAnotherService = mockFor(AnotherService)
            mockAnotherService.demand.send { String data ->
                 assert data == pData
                 return expectedResponse // not clear what a response object is - but you can return one. 
            }
            service.anotherService = mockAnotherService.createMock()  // assign your mocked Service 
    
            when:
            def response = service.method1(pData)
    
            then:
            response
            response == expectedResponse   
    
            where:
            pData << ["string one", "string two"]
        }
    }
    

    【讨论】:

    • 大家好,我也有类似的问题,但是如何在 Spock 框架中做同样的事情呢?任何示例 - 链接都会很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多