How can we use built-in jmeter functions in Groovy?
Asked Answered
B

1

5

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.

Bakelite answered 22/1, 2018 at 15:13 Comment(0)
C
9
  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

Carilyn answered 22/1, 2018 at 18:48 Comment(1)
Thank you, particularly as I now realise how to call inbuilt functions in various ways & some of the tradeoffs. It's a pity there aren't equivalent short methods similar to vars, props, etc. for these methods.Bakelite

© 2022 - 2024 — McMap. All rights reserved.