Thursday, June 23, 2016

JMeter - how to call external groovy script

Recently was problem to call external script from JMeter. It's really useful to have shared library between different scrips in JMeter. Recently I have to create separate maven project producing jar which should be placed to JMeter. It was quite time expensive and difficult to maintain and fragile. Call external script from BeanShell script is possible but it's not easy.

Luckily in JMeter 3.0 is functionality JSR223. Now it's easy task.

  • Create configuration element User defined variable and create property 'scriptHome'.
    ${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer   .getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}
    
    From now in JMeter is available variable scriptHome. Variable point to directory where is places .jmx file.
  • In directory where is placed .jmx test file create file 'helloWorld.groovy' with content:
    public class Test{
        def sayHello(){
             println "Hello world"
        }
    }
    
  • Finally create JSR223 Sampler. As script language choose Groovy. Paste following script:
    def scriptHome = vars.get("scriptHome");
    def gcl = new GroovyClassLoader()
    def clazz2 = gcl.parseClass(new File(scriptHome + "helloWorld.groovy"))
    def o = clazz2.newInstance()
    o.sayHello()
    
Now run test, on console will be output 'Hello world'.

No comments:

Post a Comment