Grails:在另一个服务中模拟服务及其方法

时间:2014-09-22 21:12:44

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

我有以下服务:

class MyMainService {

    def anotherService;

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

}

anotherService是在grails resources.groovy

中定义的bean

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

对MyMainService中的method1进行单元测试

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

我正在使用grails 2.3.8。

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用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"]
    }
}
相关问题