Reputation: 19
I'm practicing this example to validate some book price out of a json response but I'm encountering error:
Exception thrown
java.lang.AssertionError: Unable to find the title A Nice Novel. Expression: (books instanceof java.util.Map). Values: books = null at validateBookPrice.verifyBookPrice(validateBookPrice.groovy:29) at validateBookPrice$_run_closure1.doCall(validateBookPrice.groovy:22) at validateBookPrice.run(validateBookPrice.groovy:20)
Here are my code examples:
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"
}
Upvotes: 1
Views: 1198
Reputation: 21359
Here is the fixed script:
Changed from : bookData.bookStore.find{it.key == title }
To : 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)
}
You may quickly try online Demo
Upvotes: 1