gpt4 book ai didi

java - Spock - stub JSON 响应

转载 作者:行者123 更新时间:2023-12-02 13:42:09 32 4
gpt4 key购买 nike

我使用带有内置 spock 的 Grails 3.1.7。看起来我在 stub 单元测试执行期间由 Controller 呈现的服务返回值时遇到了麻烦。 Service 方法返回 null,然后 Controller 抛出 GroovyRuntimeException,提示“无法解析要调用的方法”,因为返回了“null”。

Controller 操作代码示例:

def register(RequestRegistrationCommand rrc) {
//some logic
render ajaxResponseService.composeJsonResponse(rrc)
}

服务方法代码示例:

JSON composeJsonResponse(instance, String successMessage = null) {
//some logic
[success: success, messages: messages] as JSON
}

部分测试套件代码:

//field definitions
def requestRegistrationCommand = Mock(RequestRegistrationCommand)
def ajaxResponseService = Mock(AjaxResponseService)

def setup() {
controller.ajaxResponseService = ajaxResponseService
.....
}

void "Testing register() action"() {
when: 'Passing invalid register params'
...
params.email = INVALID_EMAIL
controller.register(requestRegistrationCommand)

then: 'JSON response returned'
...
1 * ajaxResponseService.composeJsonResponse(requestRegistrationCommand) >> [asd:123] as JSON //tried plenty of things here
}

有趣的是,交互本身被触发(通过将其替换为“0 * _”进行检查,并且还放置“1 * ajaxR ... >> 'asd'”,并收到字符串不能为的错误转换为 JSON)。因此,交互可能会返回一些 stub 值,但无论如何,在大多数情况下,我尝试 Controller 的行为就好像它试图呈现 null:

groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method grails.artefact.controller.support.ResponseRenderer$Trait$Helper#render. Cannot resolve which method to invoke for [class com.tempvs.controllers.AuthController, null] due to overlapping prototypes between: [interface grails.artefact.controller.support.ResponseRenderer, interface java.lang.CharSequence] [interface grails.artefact.controller.support.ResponseRenderer, interface java.util.Map] [interface grails.artefact.controller.support.ResponseRenderer, interface org.grails.web.converters.Converter] at com.tempvs.controllers.AuthController.register(AuthController.groovy:45) at com.tempvs.controllers.AuthControllerSpec.Testing register() action(AuthControllerSpec.groovy:97)

我做错了什么?我应该如何强制模拟的服务对象返回非空值以避免 Controller 渲染失败?

如果需要更多信息,请通知我,我尽量简短。提前致谢!

UPD交互测试通过:

1 * ajaxResponseService.composeJsonResponse(requestRegistrationCommand) >> Mock(JSON)

当我将 AjaxResponseService#composeJsonResponse() 返回类型从 JSON 更改为 def 时。但是来吧,我只使用一个模拟的协作者进行测试,我怎样才能强制它支持显式类型?!?!

最佳答案

您应该使用闭包作为返回值:

1 * ajaxResponseService.composeJsonResponse(requestRegistrationCommand) >> { [asd:123] as JSON }

请参阅(请参阅有关返回值的部分):

http://spockframework.org/spock/docs/1.1-rc-3/interaction_based_testing.html

您也许可以用括号将返回值括起来:

1 * ajaxResponseService.composeJsonResponse(requestRegistrationCommand) >> ( [asd:123] as JSON )

关于java - Spock - stub JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42682422/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com