Saturday, January 2, 2016

Running a Jmeter script through Java

It may be useful to run a jmeter script through java and take actions depending on assertions in the script.

1) Creating the project


generate a java project using maven and add following dependencies,
  • ApacheJMeter_core
  • ApacheJMeter_http
  • jorphan
further dependencies[1] may need to be put if the jmeter script being run uses samplers other than http sampler or other comps such as pre-post processors.

 

2) Code


        ....
        ....   
        StandardJMeterEngine jmeter = new StandardJMeterEngine();
       
        //Initialize Properties, logging, locale, etc.
        JMeterUtils.loadJMeterProperties(JMETERPROPFILE);
        JMeterUtils.setJMeterHome(JMETERHOME);
        JMeterUtils.initLocale();
        SaveService.loadProperties();
               
        // Load existing .jmx Test Plan
        FileInputStream in = new FileInputStream(JMETERSCRIPT);
        HashTree testPlanTree = SaveService.loadTree(in);
        in.close();
       
        // Runing JMeter Test       
        Summariser summer = new Summariser();
        String testLog = JTLHOME+new Date().getTime()+".jtl";
        MyResultCollector resultCollector = new MyResultCollector(summer);
        resultCollector.setFilename(testLog);
        testPlanTree.add(testPlanTree.getArray()[0], resultCollector);      
        jmeter.configure(testPlanTree);
        jmeter.run();
        results = resultCollector.getResults();
        ....
        ....

ResultCollector class is extended so that actions can be taken based on the assertion result.

    ....
    ....   
    @Override
        public void sampleOccurred(SampleEvent e) {
        super.sampleOccurred(e);
        SampleResult r = e.getResult();
       
        ResultDTO result = new  ResultDTO();
        result.setSamplerName(r.getSampleLabel());
        result.setResponseCode(r.getResponseCode());
        result.setResult(r.isSuccessful());               
        results.add(result);
    }
    ....
    ....



Find the full example here,
https://github.com/handakumbura/jmeterrunner

No comments:

Post a Comment

What's in my Bag? EDC of a Tester