【发布时间】:2020-09-02 18:58:50
【问题描述】:
我想在 2 个 json 文件之间断言值。 这是我尝试过的代码,它工作正常,但我有 300 多个值要测试。 除了 300 行之外,还有更好的方法来使用循环:
file1.json 内容为:
[
{
"Name": "Pierre",
"Address": 1,
"City": "Paris",
"Country": "FRA",
"Code": "2020-01-01T00:00:00",
"Position": " 7000,00 $ "
},
{
"Name": "Pierre",
"Address": 2,
"City": "Paris",
"Country": "USA",
"Code": "2020-01-01T00:00:00",
"Position": " 9000,00 $ "
},
{
"Name": "Pierre",
"Address": 3,
"City": "Paris",
"Country": "GER",
"Code": "2020-01-01T00:00:00",
"Position": " 2000,00 $ "
}
]
file2.json 内容为:
{"value": {
"data": {"number1": [
[
{
"Name": "Pierre",
"Address": 1,
"City": "Paris",
"Country": "FRA",
"Code": "2020-01-01T00:00:00",
"Position": " 7000,00 $ "
},
{
"Name": "Paul",
"Address": 2,
"City": "Paris",
"Country": "USA",
"Code": "2020-01-01T00:00:00",
"Position": " 9000,00 $ "
},
{
"Name": "Pierre",
"Address": 3,
"City": "Paris",
"Country": "GER",
"Code": "2020-01-01T00:00:00",
"Position": " 2000,00 $ "
},
"Name": "Luc",
"Address": 6,
"City": "Pekin",
"Country": "CHN",
"Code": "2020-01-01T00:00:00",
"Position": " 800,00 $ "
},
]
]
}
我想用 file2 断言 file1 的每个值。 例如:
JsonSlurper jsonSlurper1 = new JsonSlurper()
File file1Actual = new File('c:/temp/file1.json')
def actualJson = jsonSlurper1.parse(file1Actual)
JsonSlurper jsonSlurper2 = new JsonSlurper()
File file2Expected = new File('c:/temp/file2.json')
def expectedJson = jsonSlurper2.parse(file2Expected)
assert actualJson.value.data.number1.Name[0] == expectedJson.Name[0]
assert actualJson.value.data.number1.Name[1] == expectedJson.Name[1]
assert actualJson.value.data.number1.Name[2] == expectedJson.Name[2]
感谢您的任何建议
【问题讨论】:
-
hi file1 有额外的 {"value": { "data": {"number1": [ 这是有意的吗?
-
您的代码示例使用的是 Groovy,而不是 Java。您可能需要编辑标签。
-
如果您不介意复杂的错误消息(对于 >300 个项目):
actualJson.value.data.number1*.Name == expectedJson*.Name -
我在单元测试中使用JSONAssert。
标签: groovy