Search code examples
jmeterjsonpath

loop through array values in jmeter Json path and assert each value


I have this filtered JSON response from Json Path exression

[40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,40,45,45,45,45,45,42,45,42,45,42,41,40,35,37,35,45,42,41,40,35,37,35,45,42,41,40,35,37,35,45]

I need to write some assertion which will basically assert these values are in a range ex: between 30 and 60. I am not getting any pointers on how to assert this in jmeter.


Solution

  • JMeter doesn't offer appropriate Test Elements so you will have to do some scripting.

    The below code assumes JMeter version is equal or higher than 3.0. For earlier JMeter versions you will have to put Json-smart libraries somewhere in JMeter Classpath

    1. Add Beanshell Assertion after the JSON Path PostProcessor
    2. Put the following code into the Beanshell Assertion "Script" area

      import net.minidev.json.JSONArray;
      import net.minidev.json.parser.JSONParser;
      import org.apache.commons.lang.math.IntRange;
      
      
      String source = vars.get("yourVar");
      
      IntRange range = new IntRange(30, 60);
      
      JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
      JSONArray array = (JSONArray) parser.parse(source);
      for (int i = 0; i < array.size(); i++) {
          int value = (int) array.get(i);
          if (!range.containsInteger(value)) {
              Failure = true;
              FailureMessage = "Detected value: " + value + " is not in the expected range";
      
          }
      
      }
      

      If the value outside the given range will be found the Beanshell Assertion will fail the parent sampler

      Beanshell assertion in work

    See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on enhancing your JMeter tests with scripting.