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