hikarthiks
hikarthiks

Reputation: 47

Validate multiple parameters in JSON Response for a specified range of values

Using JSON Extractor I managed to get the following piece of data which I need to get out of the whole JSON response. Now, I need to validate each field for a range of values for eg. ANNUALINCOME should be between say for eg. 1 - 10 L/annum, AGE 18 - 30 & EDUCATION can be B.A, B.Sc. or B.Com

{
:   "ID":"M12345",
:   "EDUCATION":"B.A.",
:   "ANNUALINCOME":"5 - 6 L\/annum",
:   "AGE":"29"
}

mid_10=
{
:   "ID":"M12346",
:   "EDUCATION":"B.Sc.",
:   "ANNUALINCOME":"1 - 2 L\/annum",
:   "AGE":"24"
}

mid_11=
{
:   "ID":"M12347",
:   "EDUCATION":"B.Com.",
:   "ANNUALINCOME":"5 - 6 L\/annum",
:   "AGE":"27"
}

Should I be using Response Assertion here? I also need to check which ID's are passed and which are failed. I should ideally be getting the failed ID even if I didn't get the passed ones.

Thanks in advance for the help.

Upvotes: 0

Views: 478

Answers (1)

Dmitri T
Dmitri T

Reputation: 168072

Your acceptance criteria are too specific hence you will not be able to use Response Assertion.

You will have to go for JSR223 Assertion and Groovy scripting, example assertion code would be something like:

def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())

def income = response.ANNUALINCOME

def lowerBound = (income =~ "(\\d+)")[0][1] as int
def upperBound = (income =~ "(\\d+)")[1][1] as int
def average = (lowerBound + upperBound) / 2
def acceptableIncomeRange = 1..10
if (!acceptableIncomeRange.contains(average)) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage('Annual income is not within the acceptable range: ' + income)
}

def acceptableAgeRange = 18..30
def age = response.AGE as int

if (!acceptableAgeRange.contains(age)) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage('Age is not within the acceptable range: ' + age)
}

def acceptableEducations = ['B.A.', 'B.Sc.', 'B.Com']
def education = response.EDUCATION

if (!acceptableEducations.contains(education)) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage('Education is not within the acceptable range: ' + education)
}

References:

Upvotes: 1

Related Questions