JulianHarty
JulianHarty

Reputation: 3286

How can we use built-in jmeter functions in Groovy?

I seem to have spent far too long trying to discover a way to obtain information such as the machineName I'd like to use https://jmeter.apache.org/usermanual/functions.html in two different programming languages, in Groovy code (rather than BeanShell, etc), and in Java.

In groovy, I have tried using ctx, vars, and props to no avail.

Similarly it'd be great to discover how to do the same in a Java Sampler. From what I can tell I can get some information e.g. the thread number using JMeterContextService.getContext().getThreadNum() but I've not found a way to interact/use the main JMeter functions.

One way might be to re-implement the functions, especially where they're described e.g. "The machineName function returns the local host name. This uses the Java method InetAddress.getLocalHost() and passes it to getHostName()" but I hope that's not necessary...

Thank you.

Upvotes: 5

Views: 2887

Answers (1)

Dmitri T
Dmitri T

Reputation: 168147

  1. The best option is putting the function call to "Parameters" section and refer its return value as Parameters or args[0] in script body like

    def machineName = Parameters
    

    JMeter Function via Parameters

  2. You can do it via instance of MachineName class like:

    def machineName = new org.apache.jmeter.functions.MachineName().compute()
    
  3. You can do it using JMeterUtils helper class like:

    def machineName = org.apache.jmeter.util.JMeterUtils.getLocalHostName()
    
  4. And finally (but this is not recommended as caching of compiled scripts won't be available) you can inline any JMeter function into script body

    def machineName = '${__machineName()}'
    

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Upvotes: 9

Related Questions