2013-02-04 57 views
6

獲取隨機值我定義了一個新的變量從一個數組

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

,並在我的道路我想從類別隨機值:category_id=my_random_value

我甚至試過這種

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

,但它不工作。

回答

5

__StringFromArrayAtRandomindex不是JMeter核心的一部分,也不是JMeter插件的一部分。

它是一個自定義函數嗎?

此外,你有一個語法錯誤(存在丟失在結束:

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

要做到同樣的事情,使用CSV數據集將包含:

1 
2 
3 
4 
5 

集:

Variable Names=categoryId 

然後,您可以使用它像這樣:

${categoryId} 
+0

沒有它不是自定義功能,有沒有用JMeter來解決這個的方法嗎? –

+1

謝謝!它的工作 –

9

對於您的情況,你可以嘗試用一點點的Java/groovy代碼使用JSR233組件(SamplerPreProcessorPostProcessor)。

例如爲:

  • 定義你的數據,你所做的:

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

    (即用逗號分隔符爲,無空格前後逗號後)。

  • 使用JSR233採樣/預處理器/ PostProcessor中使用以下代碼:

    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); 
    
  • 參考使用${rnd_cat}的隨機挑選的類別。

+0

'vars.set()' - >'vars.put()':謝謝@Thomas Solti的更新。 –

8

從列表中獲得一個隨機變量值,首先聲明爲用戶變量列表或可用值,有一個前綴和一個增量索引:

country_1  Spain 
country_2  France 
country_3  Portugal 
country_4  Italy 
country_5  England 

然後你就可以得到一個隨機值從列表中級聯前綴與在區間隨機索引:

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

說明

__Random函數將爲您提供間隔索引。要獲得1到5的值,您必須呼叫__Random(1,6,),因爲它永遠不會達到MAX值。

__V函數將獲取具有給定名稱的變量的值。

${__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... 

作爲實例,使用隨機變量作爲JSON體的請求時,在體數據:

} 
    "country":"${__V(country_${__Random(1,6,)})}" 
}