我正在使用Soapui,我想添加一个常规代码来声明json响应中的某些元素。
我如何将groovy的if else语句用于以下代码:
def jsonPayload = new File("C:/temp7/file.js").text
import groovy.json.JsonSlurper
def slurper = new JsonSlurper()
def response = slurper.parseText(jsonPayload)
if (assert response.comp.type[0] == "header")
println 'header is present'
else 'header is not present'
Run Code Online (Sandbox Code Playgroud)
当我尝试这个时,我遇到错误org.codehaus.groovy.control.MultipleCompilationErrorsException
谢谢
Groovy的编译器希望if测试中的代码能够评估结果。如果我在Groovy控制台中运行此代码
assert true
Run Code Online (Sandbox Code Playgroud)
我没有结果,如果我跑步
assert true
"asdf"
Run Code Online (Sandbox Code Playgroud)
我懂了
Result: asdf
Run Code Online (Sandbox Code Playgroud)
所以assert是一个语句,它不会评估任何东西。尝试使用assert作为if语句的条件,例如
if (assert true) {
println('hello')
}
Run Code Online (Sandbox Code Playgroud)
结果是
1 compilation error:
unexpected token: assert at line: 1, column: 5
Run Code Online (Sandbox Code Playgroud)
if的条件必须是一个表达式。
断言适用于在断言不正确的情况下您希望它大声失败的情况。不要使用assert,除非您希望它在不满足条件的情况下引发异常。
在这里,似乎可以不用断言就可以做到:
if (response.comp.type[0] == 'header')
println('header is present')
else
println('header is not present')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3666 次 |
| 最近记录: |