Get random values from an array

前端 未结 3 2077
醉话见心
醉话见心 2020-12-16 23:15

I defined a new variable

Name        Value            Description
categories  (1, 2, 3, 4, 5)  my categories ids

and in my path i want to

相关标签:
3条回答
  • 2020-12-16 23:23

    __StringFromArrayAtRandomindex is not part of JMeter core nor part of JMeter plugins.

    Is it a custom function ?

    Furthermore, you have a syntax error (there is a missing ) at end:

    ${__StringFromArrayAtRandomindex('1', '2', '3', '4', '5')}
    

    To do the same thing, use a CSV Data Set which will contain:

    1
    2
    3
    4
    5
    

    Set:

    Variable Names=categoryId
    

    You can then use it like this:

    ${categoryId} 
    
    0 讨论(0)
  • 2020-12-16 23:33

    To obtain a random variable value from a list, first declare as User variables the list or available values, with a prefix and a incremental index:

    country_1     Spain 
    country_2     France  
    country_3     Portugal  
    country_4     Italy 
    country_5     England
    

    Then you can obtain a random value from the list concatenating the prefix with a random index in the interval:

    ${__V(country_${__Random(1,6,)})}  --> "Spain", "France", "Portugal", etc...
    

    Explanation

    The __Random function will give you an index for your interval. To obtain values from 1 to 5, you have to call __Random(1,6,), as it will never reach the MAX value.

    The __V function, will obtain the value of the variable with the given name.

    ${__Random(1,6,)}                 --> 1, 2, 3, 4, 5
    country_${__Random(1,6,)}         --> "country_1", "country_2", etc...
    ${__V(country_${__Random(1,6,)})} --> "Spain", "France", "Portugal", etc...
    

    As example, to use the random variable as JSON body for a request, in Body Data:

    }
      "country":"${__V(country_${__Random(1,6,)})}"
    }
    
    0 讨论(0)
  • 2020-12-16 23:41

    For your scenario you could try to use the JSR233 components (Sampler, PreProcessor, PostProcessor) with a bit of java/groovy code.

    E.g.:

    • Define your data as you've done:

      Name        Value          
      categories  1,2,3,4,5
      

      (i.e. use comma as delimiter, no spaces before and after comma).

    • Use the JSR233 Sampler / PreProcessor / PostProcessor with the following code:

      import java.util.Random;
      
      String[] categories = (vars.get("categories")).split(",");
      
      int idx = new Random().nextInt(categories.length);
      String category = (categories[idx]);
      
      vars.put("rnd_cat", category);
      
    • Refer to the randomly picked category using ${rnd_cat}.

    0 讨论(0)
提交回复
热议问题