Monday, October 4, 2010

JMeter - random boolean value in HTTP Request with JavaScript

If you are writing a load test with JMeter you often want to send in an random Boolean value with a HTTP request.

Following JavaScript code snippet can do that:
${__javaScript(Math.round(Math.random())==1 ? "true" : "false";)} 

What the code does in detail:

The surrounding $-sign with curly brackets

${...}
This signalizes to JMeter that a variable is used.

The javaScript tag

__javaScript()
This signalizes to JMeter to interpret the containing code as JavaScript.

The JavaScript Random function

Math.random()
Returns a random decimal value between 0 and 1.

The JavaScript Round function

Math.round()
Rounds values from .5 up to 1 and values below down to 0. So in 50% of the cases you get 0 and in the other 50% the value 1.


The IF shortcut

x==1 ? "true" : "false"
This expression stands for IF(?) x equals(==) 1 then return true else(:) false.

Other Purpose:

This code could also be used to send in a value randomly with the HTTP request or leave the value blank.
${__javaScript(Math.round(Math.random())==1 ? "12345" : "";)} 

0 comments:

Post a Comment