Tuesday, January 18, 2011

jMeter Beanshell example

Okay so today I wanted to extract a value from an html form select dropdown to use later in my test samples. The select dropdown has several options and each test iteration can yield a different one. So I needed to extract the value that is already selected when the page returns. I ran across several blogs and forum entries and one hinted that with some Java experience you can you the Beanshell post-processor. Never using Beanshell before I read up and yielded this simple script to do what I needed:


import java.util.regex.Pattern;
import java.util.regex.Matcher;
String stringData = new String(data);
Pattern p = Pattern.compile("<select name=\"creditCardAccount.creditCardType\">(.*?)</select>", Pattern.DOTALL);
Matcher m = p.matcher(stringData);
if (m.find())
{
String options = m.group(1);
p = Pattern.compile("<option.*value=\"(.*?)\".*selected=\"selected\">");
m = p.matcher(options);
if (m.find()){
vars.put("CCTYPE",m.group(1));
}else{
vars.put("CCTYPE","NOT FOUND");
log.debug("options pattern = " + p.toString());
}
}else{
vars.put("CCTYPE_SELECT","bsh pattern match failed");
}

1 comment:

  1. Actually parsing HTML with Regular Expression isn't a very good idea. It's recommended to use XPath Extractor instead.

    ReplyDelete