如何在 groovy 中断言数组 json
How to assert array json in groovy
我的 JSON 回复如下所示
{
"pCategories": [
"pogc1",
"pogc16",
"pogc2",
"testc1122",
"testcat10012018",
"testcat10012019",
"testcat100120191",
"testcat11012018",
"testcat12012018",
"testcat120120181",
"testcat20112017",
"testcat20112018"
]
}
我已经使用下面的代码断言了。
def slurped = new JsonSlurper().parseText(response.asString())
assert slurped.pCategories.contains("$category")
但是出现错误。
如何解决?
因为“$category”不是字符串。它是 GStringImpl 的一个实例。
def category = 'pogc16'
assert 'pogc16'.equals("$category") // false
要修复您的代码,您可以将“$category”转换为字符串:
assert slurped.pCategories.contains("$category".toString())
这里需要一点帮助。目前还不清楚您实际要做什么。
如果 category
是一个变量,那么你不必在 contains()
中使用 "$category"
,你可以简单地使用 category
除非你正在评估一些表达式。
但如果这不是您的 use-case 而您只是想消除错误;只需在 $ 符号前添加一个转义字符:
assert slurped.pCategories.contains("$category")
如果您可以详细说明您的 use-case,也许我们可以提供帮助。
我的 JSON 回复如下所示
{
"pCategories": [
"pogc1",
"pogc16",
"pogc2",
"testc1122",
"testcat10012018",
"testcat10012019",
"testcat100120191",
"testcat11012018",
"testcat12012018",
"testcat120120181",
"testcat20112017",
"testcat20112018"
]
}
我已经使用下面的代码断言了。
def slurped = new JsonSlurper().parseText(response.asString())
assert slurped.pCategories.contains("$category")
但是出现错误。
如何解决?
因为“$category”不是字符串。它是 GStringImpl 的一个实例。
def category = 'pogc16'
assert 'pogc16'.equals("$category") // false
要修复您的代码,您可以将“$category”转换为字符串:
assert slurped.pCategories.contains("$category".toString())
这里需要一点帮助。目前还不清楚您实际要做什么。
如果 category
是一个变量,那么你不必在 contains()
中使用 "$category"
,你可以简单地使用 category
除非你正在评估一些表达式。
但如果这不是您的 use-case 而您只是想消除错误;只需在 $ 符号前添加一个转义字符:
assert slurped.pCategories.contains("$category")
如果您可以详细说明您的 use-case,也许我们可以提供帮助。