Calculating Age by custom Program

249 views Asked by At

There is one POST request which submits both Date of Birth & Age.

I found the Date of Birth from previous request, extracted it through Regular Expression Extractor, and passing the Variable in the POST request.

But I did not found the Age from the previous request. Tried figuring out the Age element through Firebug also. But it's not located, due to this field is auto calculated by the Date of Birth field and also the field is read-only.

How do I get the value of Age field?

Possible solution could be using some Jmeter in-built function or by writing some Program in any Scripting Language. But I do not know how to do it in Jmeter.

Thanks in advance.

2

There are 2 answers

0
Dmitri T On BEST ANSWER

Given that you have variable i.e. "birthdate" with the value of "1970-05-15" you can figure out person's age with the Beanshell PreProcessor as follows:

  1. Add a Beanshell PreProcessor as a child of the sampler which needs to pass birth date and age.
  2. Put the following code into the PreProcessor's "Script" area

    import java.text.SimpleDateFormat;        
    
    String birthDate = vars.get("birthDate");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
    Date dateOfBirth = sdf.parse(birthDate);
    
    Calendar dob = Calendar.getInstance();
    dob.setTime(dateOfBirth);
    Calendar today = Calendar.getInstance();
    int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
    if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
        age--;
    } else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
            && today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {
        age--;
    }
    
    vars.put("age",String.valueOf(age));
    
  3. You will be able to refer calculated age as ${age}

See SimpleDateFormat JavaDoc for explanation of "yyyy-mm-dd" pattern and information on how to define the one which matches your application date and time format and How to use BeanShell: JMeter's favorite built-in component guide to learn about scripting in JMeter.

0
JusMe On

Without seeing the response I can't say whether is can be extracted or not. A viable workaround would be to add a Post Processor to the request that the DOB is extracted from (this can be a jsr223 or beanshell) from there you can grab the DOB as such:

String dob = vars.get{"dateOfBirth"}

From there you will need to parse this into a date and compare it with the current date to get the age. You then need to put the "Age" variable so JMeter can access it.

vars.put("age", String.valueOf(age))