Search code examples
groovyjmeterjsr223

How to write JMeter variables to file on Response Assertion failure


I have a response assertion under a HTTP Request which checks to see if "Insufficient Access" is displayed when a user logs in. It's a simple text assertion.

On failure only, I want to write the user credentials to a file. I'm trying to do this via JS223 PostProcessor and so far I've only been able to find info on how to write to file using this but I can't find any info on how to check the Response Assertion first

    FileWriter fstream = new FileWriter("C:\\Loadtest\\log.txt",true); //Create New file with name "subid"
    
    BufferedWriter out = new BufferedWriter(fstream);
    
    // Need logic to check if response has failed and then do below steps
    if (assertionhasfailed)
    {
        out.write(vars.get("account"));
        out.write(System.getProperty("line.separator"));//insert new line
    }
    
    out.close();
    fstream.close();

EDIT

I resolved this issue by using a JS223 Assertion instead:

Boolean result = prev.getResponseDataAsString().contains("Insufficient privileges")

FileWriter fstream = new FileWriter("C:\\Loadtest\\log.txt",true); //Create New file with name "subid"

BufferedWriter out = new BufferedWriter(fstream);

if (result)
{
    out.write(vars.get("account"));//write value of variable 1
    out.write(System.getProperty("line.separator"));//insert new line
    AssertionResult.setFailure(true);
        AssertionResult.setFailureMessage("User has insufficient privileges");
}

out.close();
fstream.close();

Question now is whether this is the best way of doing this? I ask because I notice when running the test there is a noticeable delay when it processes the assertion. This might skew performance metrics.


Solution

  • According to JMeter Test Elements execution order:

    1. Configuration elements
    2. Pre-Processors
    3. Timers
    4. Sampler
    5. Post-Processors (unless SampleResult is null)
    6. Assertions (unless SampleResult is null)
    7. Listeners (unless SampleResult is null)

    Post-Processor is executed before the assertion therefore you don't have access to the actual status of the Sampler.

    You need to switch to the JSR223 Listener, this way you will be able to check whether the sampler is successful or not as follows:

    if (!prev.isSuccessful()) {
        //your code here
    } 
    

    where prev stands for the previous SampleResult

    More information: Top 8 JMeter Java Classes You Should Be Using with Groovy