2
votes

So I added a Response Assertion on the main sample and apply to that and all sub-samples. I assert its a good Response Code, so the assertion will fail Response codes like 4xx and 5xx errors. I'm curious, I store a user_id in a jmeter variable when a new user is created in my load script (which is available in jmeter for the entire thread/samplers/session)... Is there anyway i can output that variable via the Beanshell for All sampler requests ONLY IF there is an Error.

I already output user_id earlier for ALL requests right after creating a user via something like so:

log.info("user_id:"+ vars.get("user_id") ); //gotten via JSON Path PostProcessor earlier when creating User.

But I'd like do output something like so for all Response Assertion errors:

log.info("Response Assertion failure for user_id:"+ vars.get("user_id") );

maybe a 'BeanShell Post Processor' but dont really have a good idea how to hook that into the 1 Response Assertion whick checks the whole Thread Group so it only outputs to the log the user_id dynamically if there is Assertion failure.

Is there a worst case scenario, where I cant do it for all requests at the 'top level' of the Thread Group... but maybe I'd have to add Response Assertions on each request instead and only then I can dynamically add the output somehow? (But if there is a way of doing it once for all requests would be cool/better) Any ideas are welcome, Thanks!

1

1 Answers

2
votes
  1. You don't need a Response Assertion to check for 4xx and 5xx HTTP response codes, JMeter is smart enough to automatically mark HTTP responses with codes above 400 as failed.
  2. You can add a Beanshell Listener to print something into the log on sampler failure using code like:

    if (!sampleResult.isSuccessful()) {
        log.info("Response Assertion failure for user_id:"+ vars.get("user_id") );
    }
    

Where sampleResult is a shorthand for SampleResult class instance holding parent previous sampler result. See JavaDoc for all available methods and fields.

Depending on where you place the Beanshell Listener its scope will be different.

  • If you put it on the same level as your samplers - it will be executed after each sampler, i.e. Sampler1 and Sampler 2

    Sampler1 and Sampler2

  • If you put it as a child of the Sampler1 - it will be applied to Sampler1 only

    Sampler1

Check out How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on using Beanshell test elements in JMeter tests.