Ads 468x60px

freak2code is the blog about latest geek news,software reviews ,trends in technology and more informative stuff......

Friday, 31 August 2012

Making your JMeter tests timeless.


Making your JMeter tests timeless.


At work, we use Apache JMeter for load testing applications or API’s we build.
JMeter is an amazing open source tool with an even more amazing community behind it, so if you’ve never used it, you surely are missing on a great piece of software.
Anyway, one thing that used to annoy me a bit, was the fact that when creating tests for API’s, I’d sometimes need to pass in dates.
So imagine the following case:
You’re testing that your API can create a new book in your bookstore for a specified date, but the business rules imply that you can only create a new book with a release date in the future.
If I had hard coded this to a date in the near future, I would then need to update it at some point as to always make sure my dates really were in the future.
I could also put a date very far in the future, but my business rules again dictate that I can only pass in dates up to 60 days in advance, so I’d end up having to update my tests in about two months or so.
Come the user defined variables:
With JMeter, you can create “user defined variables” (add -> config element -> user defined variables) and assign values to it. Those variables can be created with JavaScript, so you could potentially create a variable in there, that would always default to today’s date plus a given number of days (in this example anything that didn’t exceed 60 days)
JMeter - User Defined Variables
The code for your user defined variable would look like this:
${__javaScript(var d=new Date();d.setDate(d.getDate() + 60); var date=d.getDate(); var month=d.getMonth()+1; $DATE=d.getFullYear() + "-" + (month<10?"0"+month:month) + "-" + (date<10?"0"+date:date);,DATE)}
view rawfile1.jsThis Gist is brought to you using Simple Gist Embed.
What it does is simply create a new date, add 60 days to it, and then format it as “yyyy-mm-dd”. You could change the number of days and format easily by moving things around.
A sample request would then look something like this:
&lt;book&gt;
 &lt;name&gt;The Magic Book&lt;/name&gt;
 &lt;isbn&gt;0123456789&lt;/isbn&gt;
 &lt;category&gt;children&lt;/category&gt;
 &lt;release&gt;${date}&lt;/release&gt;
&lt;/book&gt;
Which would generate a request as such:
PUT http://my.api.com/v1/books/add
PUT data:
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;book&gt;
 &lt;name&gt;The Magic Book&lt;/name&gt;
 &lt;isbn&gt;0123456789&lt;/isbn&gt;
 &lt;category&gt;children&lt;/category&gt;
 &lt;release&gt;2012-11-01&lt;/release&gt;
&lt;/book&gt;
And with that, your tests become timeless, as you can run then whenever you like without having to worry about updating dates.

0 comments:

Post a Comment

Recent Posts