Varun
Varun

Reputation: 137

How to validate json response in bean shell and perform some action in case the response is not as expected in jmeter?

I want to extract the json response in jmeter and if the response is not as expected, i need to print it to a csv file.

i tried using the contains method to check if the response contains an expected keyword but it doesn't seem to work. Is there anyother way I can do this?

Sample Code here:

log.info(ctx.getPreviousResult().getResponseDataAsString());

r = ctx.getPreviousResult().getResponseCode();

d = ctx.getPreviousResult().getResponseDataAsString();

if(!d.contains("valid")){

p.println(r +","+ vars.get("email") +",");

}

This is my json response

{
     "isBlueLinkServicePinValid": "valid"
}

I'm checking for the keyword "valid"

if(!d.contains("valid"))

But it doesn't seem to work?

TIA

Upvotes: 0

Views: 520

Answers (1)

Dmitri T
Dmitri T

Reputation: 167992

  1. Since JMeter 3.1 it is not recommended to use Beanshell for scripting, you should go for JSR223 Test Elements and Groovy language instead. The main reason is that Groovy has much better performance than Beanshell does.

  2. Groovy has built-in JSON support therefore you can extract isBlueLinkServicePinValid attribute value in an easy way:

    String response = prev.getResponseDataAsString();
    log.info("Response: " + response)
    String valid = new groovy.json.JsonSlurper().parseText(response).isBlueLinkServicePinValid
    log.info("Valid: " + valid);
    if (valid.equals("valid")) {
        log.info("Do something");
    }
    else {
        log.info("Do something else");  
    }
    

    Demo:

    enter image description here

Upvotes: 1

Related Questions