2

I have an API to fetch the list of employee Name's in an organization and it supports order by clause. I invoked an API "get /employeeName?$ordeyby=name desc". I got the results like below,

{
"value":[
{
  "name":"Sam"
},
{
  "name":"Peter"
},
{
  "name":"Harry"
},
{
  "name":"Arnold"
}]
}

I have parsed each name and stored into a variable of string type.

How can I verify using JAVA Script/BeanShell/Groovy, that the returned response is in descending order?

Can anyone please help here. Any of the above-mentioned languages is fine and I want this needs to be implemented in JMeter.

Thanks in advance.

2 Answers 2

1
  1. Add JSR223 Assertion as a child of the request which returns the above JSON
  2. Put the following code into "Script" area:

    def expected = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..name').sort().reverse()
    
    new groovy.json.JsonSlurper().parse(prev.getResponseData()).value.eachWithIndex { def entry, int i ->
        if (!entry.name.equals(expected.get(i))) {
            AssertionResult.setFailure(true)
            AssertionResult.setFailureMessage('Order mismatch, expected: ' + expected.get(i) + ', got: ' + entry.name)
        }
    }
    
  3. That's it, in case of expected alphabetical descending order the sampler will be successful, otherwise you will get an error message indicating which name is expected and what is the actual one

More information:

Sign up to request clarification or add additional context in comments.

1 Comment

This solution helped me. Thanks.
1

You can sort it in js using this approach

var employers = [
    {
      "name":"Sam"
    },
    {
      "name":"Peter"
    },
    {
      "name":"Harry"
    },
    {
      "name":"Arnold"
    }];

    console.log(employers.sort(function(e1,e2){
    var alc = e1.name.toLowerCase(), blc = e2.name.toLowerCase();
      return alc > blc ? 1 : alc < blc ? -1 : 0;
    }));

5 Comments

I'd hate to inherit that code. Nested ternaries are a bear to read and your variable names are not very descriptive...
makes sense, I provided example for you. If you hate ternaries you can use this return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
API returns the response in a sorted manner, I just want to verify the sorting of return response.
@Hari Then I suppose you could sort the response, and then compare it to the original response?
@Hari That's what we want.. for you to post the code you tried, and why you say it "didn't work".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.