我正在练习这个例子来验证json响应中的一些图书价格,但我遇到了错误:
抛出异常
java.lang.AssertionError:无法找到标题A Nice Novel。表达式:(书籍instanceof java.util.Map)。值:books = null 在validateBookPrice.verifyBookPrice(validateBookPrice.groovy:29) 在validateBookPrice $ _run_closure1.doCall(validateBookPrice.groovy:22) 在validateBookPrice.run(validateBookPrice.groovy:20)
以下是我的代码示例:
def slurper = new groovy.json.JsonSlurper()
//sample json response
def obj = '''{ "bookStore" : [ { "category" : "novel",
"author" : "Mr. J Thomas",
"title" : "A Nice Novel",
"price" : "$25.00"
},
{ "category" : "biography",
"author" : "Mrs.Jones",
"title" : "A Biography of Mr. Jones",
"price": "$35.00"
}]}'''
def bookData= slurper.parseText(obj)
//sample book prices to be validated
def books= [ "A Nice Novel" : "\$25.00", "A Biography of Mr. Jones" : "\$35.00"]
books.each{key, value ->
def expected_value ="${value}"
verifyBookPrice(bookData, key, expected_value)
}
def verifyBookPrice(bookData, title, expected_value) {
Map books = bookData.bookStore.find{it.key == title }
assert books instanceof Map:"Unable to find the title $title"
String actual_value = books.price as String
assert actual_value == expected_value:"The value of field $field is $actual_value, expecting $expected_value"
}
答案 0 :(得分:1)
这是固定的脚本:
更改自: bookData.bookStore.find{it.key == title }
收件人: bookData.bookStore.find{it.title == title}
def slurper = new groovy.json.JsonSlurper()
//sample json response
def obj = '''{ "bookStore" : [ { "category" : "novel",
"author" : "Mr. J Thomas",
"title" : "A Nice Novel",
"price" : "$25.00"
},
{ "category" : "biography",
"author" : "Mrs.Jones",
"title" : "A Biography of Mr. Jones",
"price": "$35.00"
}]}'''
def bookData= slurper.parseText(obj)
def verifyBookPrice(bookData, title, expected_value) {
Map book = bookData.bookStore.find{it.title == title}
assert book instanceof Map:"Unable to find the title $title"
String actual_value = book.price as String
assert actual_value == expected_value:"The value of field $title is $actual_value, expecting $expected_value"
}
//sample book prices to be validated
def books= [ "A Nice Novel" : "\$25.00", "A Biography of Mr. Jones" : "\$35.00"]
books.each{key, value ->
verifyBookPrice(bookData, key, value)
}
您可以快速在线试用 Demo