Home » Java » java – Jmeter: wrapper for jmeter obects in groovy script-Exceptionshub

java – Jmeter: wrapper for jmeter obects in groovy script-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

H, I have code like this in JSR223 Assertion

import groovy.json.JsonSlurper;
import org.apache.jmeter.services.FileServer;

failureMessage = "";
sampleLabel = SampleResult.getSampleLabel();

isResponseCodeCorrect("204");


def isResponseCodeCorrect(String expCode)
{
  String actualCode = prev.getResponseCode();

  if(!expCode.equals(actualCode)){

    failureMessage += "ERROR code: Expected <"+ expCode +"> but we got instead  " + actualCode + ";";           
  }
}

The question is possible to create the some code library in groovy or java and inject the objects form executed sampler (like public variables: ctx, vars, props, SamplerResult)?

The goal is to inject objects like SampleResult, AssertionResult (to invoke -> SampleResult.getSampleLabel()), AssertionResult.setFailureMessage(“failureMessage);
AssertionResult.setFailure(true); ) and own functions.

Like to have the wrapper (some object) with methods to play with Assertion, saving data to CSV … The wrapper is going to be imported to JSR223 Assertion and then I would like to call some specific methods.

The expected wrapper:

 @groovy.transform.MapConstructor
   class Foo {
    SampleResult results,
    AssertionResult assertionResult

    isResponseCodeCorrect(String expCode) {
        String actualCode = prev.getResponseCode();

    if(!expCode.equals(actualCode)){

        failureMessage += "ERROR code: Expected <"+ expCode +"> but we got instead  " + actualCode + ";";       
     assertionResult.setFailureMessage(failureMessage);
     assertionResult.setFailure(true);   

     log.error(sampleLabel + " Error is going to be saved to the logs");
     PrintLogToFile();          
       }
    }
}

JSR223 Assertion:

import org.foo. wrapper

Foo wrapper = new Foo();
wrapper.isResponseCodeCorrect("200");

Or some useful things to avoid code duplication between calls

How to&Answers:

You can compile your Groovy or Java code into a .jar file and drop it into JMeter Classpath

Once done you will be able to access the functions available in the .jar file from any JSR223 Test Element and/or from __groovy() function.

I can think only of one class which you need: JMeterContext an instance of which can be obtained as simple as:

def ctx = org.apache.jmeter.threads.JMeterContextService.getContext()

once done you will be able to access whatever you need like:

  • SampleResult == ctx.getPreviousResult()
  • AssertionResult == ctx.getPreviousResult().getAssertionResults()
  • vars == ctx.getVariables()
  • props == ctx.getProperties()
  • etc.

Check out How to Reuse Your JMeter Code with JAR Files and Save Time article for more details if needed.