简体   繁体   中英

Jmeter: wrapper for jmeter obects in groovy script

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

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

Once done you will be able to access the functions available in the .jar file from anyJSR223 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM