0
votes

I have written below script in Beanshell assertion to validate some specific value:

import org.json.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

String jsonString = prev.getResponseDataAsString();
JSONObject responseJson = new JSONObject(jsonString);
String lastName = responseJson.getString("$data[0]."{last_name}"");

String Message= "";

if (lastName== "lawson")
{
Failure= false; Message= Message+"Correct value";
FailureMessage= Message;

}
else if (lastName != "lawson")
{
Failure= true;
Message= Message+"Incorrect value"+lastName;
FailureMessage= Message;
}

Below is the Json: { "per_page": 6, "total": 12, "data": [ { "last_name": "Lawson", "id": 7, "avatar": "https://reqres.in/img/faces/7-image.jpg", "first_name": "Michael", "email": "[email protected]" }, { "last_name": "Ferguson", "id": 8, "avatar": "https://reqres.in/img/faces/8-image.jpg", "first_name": "Lindsay", "email": "[email protected]" }, { "last_name": "Funke", "id": 9, "avatar": "https://reqres.in/img/faces/9-image.jpg", "first_name": "Tobias", "email": "[email protected]" }, { "last_name": "Fields", "id": 10, "avatar": "https://reqres.in/img/faces/10-image.jpg", "first_name": "Byron", "email": "[email protected]" }, { "last_name": "Edwards", "id": 11, "avatar": "https://reqres.in/img/faces/11-image.jpg", "first_name": "George", "email": "[email protected]" }, { "last_name": "Howell", "id": 12, "avatar": "https://reqres.in/img/faces/12-image.jpg", "first_name": "Rachel", "email": "[email protected]" } ], "page": 2, "total_pages": 2, "support": { "text": "To keep ReqRes free, contributions towards server costs are appreciated!", "url": "https://reqres.in/#support-heading" } }

But I am getting below error:

Assertion failure message:org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``import org.json.*; import org.json.JSONArray; import org.json.JSONException; imp . . . '' Encountered "( "$data[0]." { last_name } """ at line 9, column 41.

Can someone please help me what mistake I am making in my script?

1

1 Answers

0
votes

There are multiple problems with your code like:

So if you want to continue with code-based approach minimal equivalent code for the JSR223 Assertion would be something like:

def responseJson = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def lastName = responseJson.data[0].last_name

if (lastName != 'Lawson') {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage("Incorrect value" + lastName)
}

Be informed that you can achieve the same using JSON Assertion:

enter image description here