Search code examples
jsongroovyjmeter

Jmeter: how to construct JSON Path using field names from csv file to compare data from API response with data from DB


I have an API which returns following response:

 {
    "data": {
        "response": {
            "employee": 
                {
                   "firstName": "Frank",
                   "lastName": "Porter",
                   "employeeNumber": "11102"
                }
            }
        }
}

In JMeter, I need to do the following:

  1. Query the DB and fetch data from the tables. Store it in a variable to compare with API response.
  2. Write assertion which will compare the data from the DB with the API response. For this I need the assertion to read names of fields to compare from a CSV file.

I am able to construct a csv which has the list of fields - firstName,lastName,employeeNumber In my assertion, I am parsing the API response using JSONSlurper and then trying to compare the data. If I hardcode the field names, the comparison works ok - so something like below works ok:

import groovy.json.JsonSlurper;
def failureMessage = "";
def jsonResponse = null;
JsonSlurper JSON = new JsonSlurper ();

//compare data from db with API response

if (!jsonResponse.data.response.employee.firstName.equals(vars.getObject("datafromDB").get(0).get("firstName"))) 
{
          failureMessage += "firstName does not match \n\n";
}

if (failureMessage?.trim()) {
              AssertionResult.setFailureMessage(failureMessage);
     AssertionResult.setFailure(true);    
}
// Print error messages if any
if (failureMessage?.trim()) {
    failureMessage += "URL: " + SampleResult.getURL() + "\n\n";     
    failureMessage += "JSON RESPONSE: " + jsonResponse + "\n\n";
    AssertionResult.setFailureMessage(failureMessage);
    AssertionResult.setFailure(true);    
}

But I am not able to find a way to use the field names from the csv file. I have tried below but it does not work.

        String[] basefields = vars.getObject("getEmployeeFields").split(',');
        for(String t : basefields) {
            log.info("validating "+t);

        for (int i; i < vars.getObject("dataFromDB").size(); i++) {      
            if (!jsonResponse.data.GetClientById.t.equals(vars.getObject("datafromDB").get(0).get("t"))) //--this is where i need to construct the path using the value from csv. Field names are same between API response and DB. So, I am using t in both places
                {
                    failureMessage += "Cli_no does not match \n\n";
                }
            }

Can anyone guide me as to how to achieve this? I am using JSR 223 Assertion with groovy


Solution

  • the easiest way - Eval.me

    def jsonResponse = new JsonSlurper().parse(...)
    def jpath = 'BODY.data.response.employee.firstName' // get it from where you want
    assert Eval.me('BODY', jsonResponse, jpath)=='Frank'