1

I need to add user parameter preprocessor in the JMeter test plan via java code.

This user parameter should be passed to path parameter in Http sampler get API like" api/users/${userId}"

2 Answers 2

1

Here is how you can initialise an empty User Parameters element:

UserParameters userParameters = new UserParameters();
userParameters.setName("User Parameters");
userParameters.setProperty(new BooleanProperty("UserParameters.per_iteration", false));
userParameters.setProperty(new CollectionProperty("UserParameters.names", new LinkedList<>()));
userParameters.setProperty(new CollectionProperty("UserParameters.thread_values", new LinkedList<>()));
userParameters.setProperty(TestElement.TEST_CLASS, UserParameters.class.getName());
userParameters.setProperty(UserParameters.GUI_CLASS, UserParametersGui.class.getName());

If you need more assistance with regards to how to fill variable names/values you need to be more specific and explain what configuration you need or attach screenshot of the User Parameters element with your values

Full code just in case:

package com.example;

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.modifiers.UserParameters;
import org.apache.jmeter.modifiers.gui.UserParametersGui;
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.testelement.property.BooleanProperty;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.threads.gui.ThreadGroupGui;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.LinkedList;


public class HttpRequestWithUserParameters {

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

        File jmeterHome = new File("/path/to/your/jmeter/installation");
        String slash = System.getProperty("file.separator");


        File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");
        if (jmeterProperties.exists()) {
            //JMeter Engine
            StandardJMeterEngine jmeter = new StandardJMeterEngine();

            //JMeter initialization (properties, log levels, locale, etc)
            JMeterUtils.setJMeterHome(jmeterHome.getPath());
            JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
            JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
            JMeterUtils.initLocale();

            // JMeter Test Plan, basically JOrphan HashTree
            HashTree testPlanTree = new HashTree();

            // HTTP Sampler - open example.com
            HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
            examplecomSampler.setDomain("example.com");
            examplecomSampler.setPort(80);
            examplecomSampler.setPath("/api/users/${userId}");
            examplecomSampler.setMethod("GET");
            examplecomSampler.setName("Open example.com");
            examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

            //User Parameters
            UserParameters userParameters = new UserParameters();
            userParameters.setName("User Parameters");
            userParameters.setProperty(new BooleanProperty("UserParameters.per_iteration", false));
            userParameters.setProperty(new CollectionProperty("UserParameters.names", new LinkedList<>()));
            userParameters.setProperty(new CollectionProperty("UserParameters.thread_values", new LinkedList<>()));
            userParameters.setProperty(TestElement.TEST_CLASS, UserParameters.class.getName());
            userParameters.setProperty(UserParameters.GUI_CLASS, UserParametersGui.class.getName());


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

            // Thread Group
            ThreadGroup threadGroup = new ThreadGroup();
            threadGroup.setName("Example Thread Group");
            threadGroup.setNumThreads(1);
            threadGroup.setRampUp(1);
            threadGroup.setSamplerController(loopController);
            threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
            threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.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 initialised elements
            testPlanTree.add(testPlan);
            HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
            threadGroupHashTree.add(examplecomSampler, userParameters);

            // save generated test plan to JMeter's .jmx file format
            SaveService.saveTree(testPlanTree, new FileOutputStream(jmeterHome + slash + "example.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 = jmeterHome + slash + "example.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 " + jmeterHome + slash + "example.jtl file for results");
            System.out.println("JMeter .jmx script is available at " + jmeterHome + slash + "example.jmx");
            System.exit(0);

        }
    }
}

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick response. Could you please help me to add the values in user parameter. I have tried the below line of code . It seems that userId value is not getting replaced while execution.
LinkedList<String> names=new LinkedList<String>(); names.add("userId"); LinkedList<String> values=new LinkedList<String>(); names.add("1"); userParameters.setProperty(new CollectionProperty("UserParameters.names", names)); userParameters.setProperty(new CollectionProperty("UserParameters.thread_values", values)); error as open example.com,404,Not Found,Example Thread Group 1-1,text,false,,676,124,1,1,reqres.in/api/users/userId,3498,0,2719
1

Add JSR223 PreProcessor with java code:

 vars.put("userId", "YOUR_VALUE");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.