Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running JMeter in Java code - JMeterThread does not run sampler

Tags:

java

jmeter

So I am using this example in my maven project:

public class JMeterFromScratch {

public static void main(String[] argv) throws Exception {

    //JMeter Engine
    StandardJMeterEngine jmeter = new StandardJMeterEngine();

    //JMeter initialization (properties, log levels, locale, etc)
    JMeterUtils.loadJMeterProperties("C:/git/my-project/src/main/resources/config/jmeter.properties");
    //JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
    JMeterUtils.initLocale();

    // JMeter Test Plan
    HashTree testPlanTree = new HashTree();

    // HTTP Sampler
    HTTPSampler httpSampler = new HTTPSampler();
    httpSampler.setDomain("example.com");
    httpSampler.setPort(80);
    httpSampler.setPath("/");
    httpSampler.setMethod("GET");

    // Loop Controller
    TestElement loopController = new LoopController();
    ((LoopController)loopController).setLoops(1);
    loopController.addTestElement(httpSampler);
    ((LoopController)loopController).setFirst(true);
    ((LoopController)loopController).initialize();

    // Thread Group

    SetupThreadGroup threadGroup = new SetupThreadGroup();
    threadGroup.setNumThreads(1);
    threadGroup.setRampUp(1);
    threadGroup.setSamplerController(((LoopController)loopController));

    // Test Plan
    TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");

    // Construct Test Plan from previously initialized elements
    testPlanTree.add("testPlan", testPlan);
    testPlanTree.add("loopController", loopController);
    testPlanTree.add("threadGroup", threadGroup);
    testPlanTree.add("httpSampler", httpSampler);

    // Run Test Plan
    jmeter.configure(testPlanTree);
    jmeter.run();

}

}

In which I have the following dependencies:

    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_core</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_http</artifactId>
        <version>2.13</version>
    </dependency>

Strangely what I see is that in the ThreadGroup class, in makeThread() method, there is this line:

JMeterThread jmeterThread = new JMeterThread(this.cloneTree(threadGroupTree), this, notifier);

The call to cloneTree seems to indeed clone the tree, but absent the Sampler inside the LoopController. So when JMeterThread gets to here:

Sampler sampler = this.threadGroupLoopController.next(); // returns null

            while(true) {
                while(this.running && sampler != null) {

The sampler is null and so there is nothing to execute.

So what am I doing wrong?

Thanks.

like image 680
Nom1fan Avatar asked Feb 15 '17 08:02

Nom1fan


2 Answers

  1. I don't like version mismatch in your pom.xml, I believe you should be using <version>3.1</version> for both components
  2. I don't like the way you're building your Test Plan, it should rather be something like:

    testPlanTree.add(testPlan);
    HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
    threadGroupHashTree.add(httpSampler);
    
  3. I think you should add logging into .jtl file in order to be able to see results

Full code just in case:

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.config.gui.ArgumentsPanel;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.LoopControlPanel;
import org.apache.jmeter.control.gui.TestPlanGui;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.threads.SetupThreadGroup;
import org.apache.jmeter.threads.gui.SetupThreadGroupGui;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;

import java.io.FileOutputStream;

public class JMeterFromScratch {

    public static void main(String[] args) throws Exception {
        //JMeter Engine
        StandardJMeterEngine jmeter = new StandardJMeterEngine();

        //JMeter initialization (properties, log levels, locale, etc)
        JMeterUtils.loadJMeterProperties("/path/to/jmeter/bin/jmeter.properties");
        JMeterUtils.setJMeterHome("/path/to/jmeter/");            
        JMeterUtils.initLocale();

        // JMeter Test Plan
        HashTree testPlanTree = new HashTree();

        // HTTP Sampler
        HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
        httpSampler.setName("HTTP Request");
        httpSampler.setDomain("example.com");
        httpSampler.setPort(80);
        httpSampler.setPath("/");
        httpSampler.setMethod("GET");
        httpSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
        httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());


        // Loop Controller
        TestElement loopController = new LoopController();
        ((LoopController) loopController).setLoops(1);
        loopController.addTestElement(httpSampler);
        ((LoopController) loopController).setFirst(true);
        loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
        loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
        ((LoopController) loopController).initialize();

        // Thread Group

        SetupThreadGroup threadGroup = new SetupThreadGroup();
        threadGroup.setNumThreads(1);
        threadGroup.setRampUp(1);
        threadGroup.setName("setUp Thread Group");
        threadGroup.setSamplerController(((LoopController) loopController));
        threadGroup.setProperty(TestElement.TEST_CLASS, SetupThreadGroup.class.getName());
        threadGroup.setProperty(TestElement.GUI_CLASS, SetupThreadGroupGui.class.getName());

        // Test Plan
        TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
        testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
        testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
        testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

        // Construct Test Plan from previously initialized elements
        testPlanTree.add(testPlan);
        HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
        threadGroupHashTree.add(httpSampler);


        // save generated test plan to JMeter's .jmx file format
        SaveService.saveTree(testPlanTree, new FileOutputStream("test.jmx"));

        //add Summarizer output to get test progress in stdout like:
        // summary =      2 in   1.3s =    1.5/s Avg:   631 Min:   290 Max:   973 Err:     0 (0.00%)
        Summariser summer = null;
        String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
        if (summariserName.length() > 0) {
            summer = new Summariser(summariserName);
        }


        // Store execution results into a .jtl file
        String logFile = "test.jtl";
        ResultCollector logger = new ResultCollector(summer);
        logger.setFilename(logFile);
        testPlanTree.add(testPlanTree.getArray()[0], logger);

        // Run Test Plan
        jmeter.configure(testPlanTree);
        jmeter.run();

        System.out.println("Test completed. See test.jtl file for results");
        System.out.println("Open test.jmx file in JMeter GUI to validate the code");
        System.exit(0);
    }
}

You can use https://bitbucket.org/blazemeter/jmeter-from-code/ repo mentioned in the Five Ways To Launch a JMeter Test without Using the JMeter GUI article to get reference working code.

like image 54
Dmitri T Avatar answered Oct 13 '22 21:10

Dmitri T


I've tried several ways to create a test plan from Java, but always faced the same problem: threadGroup was created and triggered, but HTTPSampler and LoopController were not run.

Only an answer above really helped me (all the JMeter dependencies were of version 5 in Maven).

Be aware, that Blazemeter and the rest of sites reposting the same Java config to make it work are out-of-date and you need to write the code according to @Dmirti T approach.

Here is my repo with JMeter sample requestsenter link description here

like image 29
ryzhman Avatar answered Oct 13 '22 22:10

ryzhman