1
votes

I have tried my best but I had no luck in looking for a solution. Basically I needed to pass custom property when running Jmeter via java code without adding anything in the jmx file (just like when running via command line). I have some tried jmeter property functions (StandardJmeterEngine setProperty, JmeterUtils setProperty) but still no avail. I have seen some solutions like passing the property file to the code but it seems that the property file is not being read.

By the way, the easiest way to do this is to create the jmx file along with the properties via java code, but I am required to pass the property when running an existing jmx file.

public class TestRunJmxJava {

    @Test
    public static void executeScript() throws IOException, BiffException, JMeterEngineException {

        String slash = System.getProperty("file.separator");
        StandardJMeterEngine jmeter = new StandardJMeterEngine();

        String jmeterPath = "C:"+slash+"jmeter"+slash+"bin"+slash+"jmeter.properties";
        String uPath = "C:"+slash+"jmeter"+slash+"bin"+slash+"jd.properties";

        System.out.println(jmeterPath);

        JMeterUtils.setJMeterHome("C:\\jmeter");
        JMeterUtils.loadJMeterProperties(jmeterPath);
        JMeterUtils.loadProperties(uPath);

        JMeterUtils.getSearchPaths();
        JMeterUtils.initLogging();
        JMeterUtils.initLocale();

        SaveService.loadProperties();

        File in = new File(System.getProperty("user.dir")+slash+"jmxfolder"+slash+"TestJmeterRun.jmx");
        HashTree testPlanTree = SaveService.loadTree(in);

        jmeter.configure(testPlanTree);
        FileServer.getFileServer().setBasedir(System.getProperty("user.dir")+slash+"jmxfolder");
        System.out.println(FileServer.getFileServer().getBaseDir());

        Summariser summer = null;
        String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");//$NON-NLS-1$
        if (summariserName.length() > 0) {
            summer = new Summariser(summariserName);
        }

        String logFile = "C:\\Users\\JD\\Desktop\\sample2.jtl";

        ResultCollector logger = new ResultCollector(summer);
        logger.setFilename(logFile);

        testPlanTree.add(testPlanTree.getArray()[0], logger);

        jmeter.run();
        jmeter.exit();
    }
}
1

1 Answers

2
votes

You can use "normal" Java System Properties for this, they can be set in different ways:

  • Via system.properties file (lives in the "bin" folder of your JMeter installation
  • Via -D command-line argument passed to Java executable

    java -Dfoo=bar -jar /path/to/your/test.jar
    
  • Via Java code by calling System.setProperty() method

    System.setProperty("foo", "bar");
    

In all cases you should be able to access the property value like ${__P(foo,)} (make sure you include ApacheJMeter_functions.jar in your project classpath)

More information: