在Spock中使用带返回值的PollingConditions遇赋值报错
问题:PollingConditions.eventually代码块中能否进行赋值操作?
用户希望使用PollingConditions.eventually执行逻辑并返回值,代码示例如下:
@Shared static PollingConditions POLLING_CONDITIONS = new PollingConditions( timeout: 30, delay: 1.5, factor: 1.25 ) MyResponseContainerDto sendRequestWithRetries(String body, String uri) { ExtractableResponse<Response> extractedResponse = null POLLING_CONDITIONS.eventually { extractedResponse = sendRequest(body, uri).extract() assert extractedResponse.statusCode() == 200 } return extractedResponse.as(MyResponseContainerDto.class) } ValidatableResponse sendRequest(String body, String uri) { return RestAssured.given() .contentType(JSON) .body(body) .when() .post("/myApi" + "/" + uri) .then() .log().all() }
运行上述代码时出现如下错误:
Expected a condition, but found an assignment. Did you intend to write '==' ? @ line 42, column 12. extractedResponse = sendRequest(body, uri).extract() ^
请问是否可以在eventually代码块中进行赋值操作?
解答
PollingConditions.eventually要求传入的闭包最终返回一个布尔值,用来判断轮询是否终止。你的代码报错是因为闭包第一行是赋值操作,Groovy会将赋值结果(即extractedResponse对象)当作闭包返回值,这不是布尔类型,触发了语法检查的提示。
可以在eventually代码块中进行赋值,但需要调整闭包结构,确保最终返回布尔值或通过断言触发重试:
方案1:调整闭包,显式返回布尔值
保留赋值操作,在闭包末尾返回布尔判断结果,同时保留断言确保失败时重试:
POLLING_CONDITIONS.eventually { extractedResponse = sendRequest(body, uri).extract() def isStatusOk = extractedResponse.statusCode() == 200 assert isStatusOk isStatusOk // 显式返回布尔值,告知轮询条件满足 }
方案2:让闭包直接返回目标对象(更简洁)
利用eventually闭包的返回值特性,直接在闭包内返回符合条件的响应,外部变量接收这个返回值:
MyResponseContainerDto sendRequestWithRetries(String body, String uri) { ExtractableResponse<Response> extractedResponse = POLLING_CONDITIONS.eventually { def response = sendRequest(body, uri).extract() assert response.statusCode() == 200 response // 闭包返回符合条件的响应,最终赋值给外部变量 } return extractedResponse.as(MyResponseContainerDto.class) }
两种方案都能实现需求,方案2更符合Groovy的简洁风格,也避免了外部变量初始化null的冗余操作。
内容的提问来源于stack exchange,提问作者pixel
相关产品推荐
相关产品推荐

