Search code examples
selenium-webdriverjmeter-plugins

How to run jmeter performance tests in selenium webdriver framework


I am new to Jmeter. Is there a way where we can add the Jmeter plugin to my class package and create threads and run integration? Without bringing jmeter tool or interface in the picture?


Solution

  • It is possible to run existing JMeter tests from Java code using JMeter API in general and StandardJMeterEngine class in particular.

    1. Add necessary JMeter libraries to your project classpath either by adding everything from "lib" and "lib/ext" folders of your JMeter installation or including required individual packages from i.e. Maven Central, the choice depends on what functionality do you need
    2. Add a relevant JUnit or TestNG unit test which will kick off your JMeter test like:

      import org.apache.jmeter.engine.StandardJMeterEngine;
      import org.apache.jmeter.reporters.ResultCollector;
      import org.apache.jmeter.reporters.Summariser;
      import org.apache.jmeter.save.SaveService;
      import org.apache.jmeter.util.JMeterUtils;
      import org.apache.jorphan.collections.HashTree;
      import org.junit.Test;
      
      import java.io.File;
      
      public class RunJMeterTest {
      
          @Test
          public void executeJMeterTest() throws Exception {
              StandardJMeterEngine jmeter = new StandardJMeterEngine();
      
              JMeterUtils.loadJMeterProperties("/path/to/your/jmeter/bin/jmeter.properties");
              JMeterUtils.setJMeterHome("/path/to/your/jmeter");
              JMeterUtils.initLocale();
      
              SaveService.loadProperties();
      
              HashTree testPlanTree = SaveService.loadTree(new File("/path/to/your/jmeter/extras/Test.jmx"));
              Summariser summer = null;
              String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
              if (summariserName.length() > 0) {
                  summer = new Summariser(summariserName);
              }
              String logFile = "/path/to/test/result.jtl";
              ResultCollector logger = new ResultCollector(summer);
              logger.setFilename(logFile);
              testPlanTree.add(testPlanTree.getArray()[0], logger);
      
              jmeter.configure(testPlanTree);
              jmeter.run();
          }
      }
      
    3. Amend path to JMeter, to .jmx script file and to results file and you should be good to go.

    More information: Five Ways To Launch a JMeter Test without Using the JMeter GUI