I am constructing a .jmx file for jmeter GUI from Java. The .jmx only compose by http proxy samplers and threads groups. Both thread groups and proxy samplers are constructed based on a list, and ,thus, they are being arranged with a certain order. However, my problem is that the constructed .jmx has completely wrong order when comparing with the list.
I have read and try "Five Ways To Launch a JMeter Test without Using the JMeter GUI". What I did is trying to generalize the "Creating a New JMeter Test Purely in Java" to multiple thread groups and http proxy samplers. Here is the minimum code that I have worked on:
public static void createJmx(ArrayList<ArrayList<String>> calls, ArrayList<HashMap<String, String>> httpSamplerList) throws Exception {
// get log file length
int numberOfCalls = calls.size();
int numberOfhttpSampler = httpSamplerList.size();
// Engine
StandardJMeterEngine jm = new StandardJMeterEngine();
String jmeterHome = "D:\\Jenkins-Global-Workspace\\apache-jmeter-5.1.1";
// jmeter.properties
JMeterUtils.setJMeterHome(jmeterHome);
JMeterUtils.loadJMeterProperties("D:\\Jenkins-Global-Workspace\\apache-jmeter-5.1.1\\bin\\jmeter.properties");
JMeterUtils.initLogging();
JMeterUtils.initLocale();
// Create HashTree structure
HashTree testPlanTree = new HashTree();
TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
testPlanTree.add(testPlan);
HTTPSamplerProxy examplecomSampler = null;
LoopController loopController;
ThreadGroup threadGroup = null;
HashTree threadGroupHashTree = null;
int j=0;
for (int i = 0; i < numberOfCalls; i++) {
if (calls.get(i).size() == 3) {
System.out.println(calls.get(i));
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();
threadGroup = new ThreadGroup();
threadGroup.setName(calls.get(i).get(1));
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());
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());
threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
}
else {
System.out.println(calls.get(i));
examplecomSampler = new HTTPSamplerProxy();
examplecomSampler.setDomain("example.com");
examplecomSampler.setPort(80);
examplecomSampler.setPath("/");
examplecomSampler.setMethod("GET");
examplecomSampler.setName(Integer.toString(j)); // currently use a integer number naming as test
examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
threadGroupHashTree.add(examplecomSampler);
j++;
}
}
// // save generated test plan to JMeter's .jmx file format
SaveService.saveTree(testPlanTree, new FileOutputStream(".\\test.jmx"));
//
}
I am using a variable j to keep track the order of http sampler , but some http samplers are complete in wrong wrong order.
Does some one know why and how to fix it?
cheers
For those who stumbles to this post. If you have multiple modules in a hash tree and you want them to be in the same order as you add them to the tree. Please use
org.apache.jorphan.collections.ListedHashTree;
instead of
org.apache.jorphan.collections.HashTree;
Related
I want to create jmeter(.jmx) file dynamically in java using JMeterAPI and run the file using non-GUI mode. But while trying to generate the ".jmx" file its not generated as expected. It would be helpful that if I could get an working sample.
I had tried the below code:
JMeterUtils.loadJMeterProperties("jmeter.properties");
HashTree hashTree = new HashTree();
HTTPSampler httpSampler = new HTTPSampler();
httpSampler.setDomain("localhost");
httpSampler.setPort(5000);
httpSampler.setPath("/api/v1/data");
httpSampler.setMethod("GET");
TestElement loopCtrl = new LoopController();
((LoopController)loopCtrl).setLoops(1);
((LoopController)loopCtrl).addTestElement(httpSampler);
((LoopController)loopCtrl).setFirst(true);
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController((LoopController)loopCtrl);
TestPlan testPlan = new TestPlan("MY TEST PLAN");
hashTree.add("testPlan", testPlan);
hashTree.add("loopCtrl", loopCtrl);
hashTree.add("threadGroup", threadGroup);
hashTree.add("httpSampler", httpSampler);
try {SaveService.saveTree(hashTree, new FileOutputStream("jmxFile.jmx"));}
catch(Exception ex) {ex.printStackTrace();}
But I am not getting the JMX file as expected. Instead I am getting the resultant in the file as below:
Jmx File Genrated
You're missing few important things:
You need to call JMeterUtils.setJMeterHome() function and provide the path to your JMeter installation
You need to set TestElement.TEST_CLASS and TestElement.GUI_CLASS to their respective values
Example working code which produces a .jmx script which can be opened in JMeter GUI without issues (as of JMeter 5.5):
File jmeterHome = new File("/Users/dtikhanski/Applications/jmeter");
String slash = System.getProperty("file.separator");
File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");
JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
JMeterUtils.setJMeterHome(jmeterHome.getPath());
HashTree hashTree = new HashTree();
HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
examplecomSampler.setDomain("localhost");
examplecomSampler.setPort(5000);
examplecomSampler.setPath("/api/v1/data");
examplecomSampler.setMethod("GET");
examplecomSampler.setName("GET http://localhost:5000/api/v1/data");
examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
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();
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setName("Example Thread Group");
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
threadGroup.setProperty(TestElement.TEST_CLASS, SetupThreadGroup.class.getName());
threadGroup.setProperty(TestElement.GUI_CLASS, SetupThreadGroupGui.class.getName());
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());
hashTree.add(testPlan);
HashTree threadGroupHashTree = hashTree.add(testPlan, threadGroup);
threadGroupHashTree.add(examplecomSampler);
SaveService.saveTree(hashTree, new FileOutputStream("jmxFile.jmx"));
More information:
JMeter Command Line Overview: 5 Ways To Launch a Test
jmeter-from-code example project
I am new to Jmeter and my current requirement is to create a JMeter Test Plan using JSR223 Sampler in Java and then trigger it.
First step I tried is to run the jmx file(which is using JSR223 Sampler and java code snippet in script area) through Java but getting below error - javax.scripts.ScriptException: Cannot find engine named : '
java', ensure you set language field in JSR223 Test Element: JSR223 Sampler.
My Code:
File jmeterHome = new File(System.getProperty("jmeter.home"));
String slash = System.getProperty("file.separator");
if (jmeterHome.exists()) {
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();
SaveService.loadProperties();
// JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = SaveService.loadTree(new File(JMX FILE PATH))
// Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();
}
}
If you want to "create" a test plan you're really supposed to "create" it and it sounds like you want to copy and paste a ready solution from online sources or ask someone to write the script for you.
I would expect you to show your code and highlight the problematic place rather than asking to implement a test plan.
Whatever.
Here is how you can instantiate a JSR223 Sampler using Java code:
JSR223Sampler jsr223Sampler = new JSR223Sampler();
jsr223Sampler.setName("JSR223 Sampler");
jsr223Sampler.setProperty("cacheKey", "true");
jsr223Sampler.setProperty("script", "println('Hello')");
jsr223Sampler.setProperty("scriptLanguage", "groovy");
jsr223Sampler.setProperty(TestElement.TEST_CLASS, JSR223Sampler.class.getName());
jsr223Sampler.setProperty(TestElement.GUI_CLASS, TestBeanGUI.class.getName());
Full class 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.java.sampler.JSR223Sampler;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.testbeans.gui.TestBeanGUI;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
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;
public class JMeterFromScratch {
public static void main(String[] argv) throws Exception {
File jmeterHome = new File(System.getProperty("jmeter.home"));
String slash = System.getProperty("file.separator");
if (jmeterHome.exists()) {
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();
// JSR223 Sampler
JSR223Sampler jsr223Sampler = new JSR223Sampler();
jsr223Sampler.setName("JSR223 Sampler");
jsr223Sampler.setProperty("cacheKey", "true");
jsr223Sampler.setProperty("script", "println('Hello')");
jsr223Sampler.setProperty("scriptLanguage", "groovy");
jsr223Sampler.setProperty(TestElement.TEST_CLASS, JSR223Sampler.class.getName());
jsr223Sampler.setProperty(TestElement.GUI_CLASS, TestBeanGUI.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 initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(jsr223Sampler);
// 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);
}
}
System.err.println("jmeter.home property is not set or pointing to incorrect location");
System.exit(1);
}
}
References:
Five Ways To Launch a JMeter Test without Using the JMeter GUI
jmeter-from-code example repository
JSR223Sampler JavaDoc
I am trying to Connect jmeter remotely through my Java code (non-gui jmeter), but I am getting an error: rconfigure() method java.rmi.UnmarshalException
Here is my Code:
public static void main(String[] argv) throws Exception {
// Set jmeter home path
File jmeterHome = new File("E:\\apache-jmeter-3.2");
if (jmeterHome.exists()) {
// Inserting the properties of Jmeter.
File jmeterProperties = new File(
"E:\\apache-jmeter-3.2\\bin\\jmeter.properties");
if (jmeterProperties.exists()) {
// Creating JMeter Engine
StandardJMeterEngine jmeter = new StandardJMeterEngine();
// JMeter initialization (properties, log levels, locale, etc)
JMeterUtils.setJMeterHome(jmeterHome.getPath());
JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
// you can comment this line out to see extra log messages of
// i.e DEBUG level
JMeterUtils.initLogging();
JMeterUtils.initLocale();
// JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
// First HTTP Sampler
HTTPSamplerProxy sampler = new HTTPSamplerProxy();
sampler.setDomain("https://google.com/");
sampler.setPort(8080);
sampler.setPath("/");
sampler.setMethod("GET");
sampler.setProperty(TestElement.TEST_CLASS,
HTTPSamplerProxy.class.getName());
sampler.setProperty(TestElement.GUI_CLASS,
HttpTestSampleGui.class.getName());
// Loop Controller
LoopController loopController = new LoopController();
loopController.setLoops(10);
loopController.setFirst(true);
loopController.setProperty(TestElement.TEST_CLASS,
LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS,
LoopControlPanel.class.getName());
loopController.initialize();
// InterleaveControler
// InterleaveControl controller = new InterleaveControl();
// Thread Group
ThreadGroup threadGroup = new ThreadGroup();
threadGroup.setName("Sample Thread Group");
threadGroup.setNumThreads(100);
threadGroup.setRampUp(10);
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("Test planing");
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(sampler);
// save generated test plan to JMeter's .jmx file format
SaveService.loadProperties();
SaveService.saveTree(testPlanTree, new FileOutputStream(
"E:\\JunitJArs\\junitjunitjmeter_api.csv"));
// 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, we can save file as
// csv also
String reportFile = "C:\\Users\\User\\Desktop\\Jmeter\\new\\report.jtl";
String csvFile = "C:\\Users\\User\\Desktop\\Jmeter\\new\\report.csv";
ResultCollector logger = new ResultCollector(summer);
logger.setFilename(reportFile);
ResultCollector csvlogger = new ResultCollector(summer);
csvlogger.setFilename(csvFile);
testPlanTree.add(testPlanTree.getArray()[0], logger);
testPlanTree.add(testPlanTree.getArray()[0], csvlogger);
// Run Test Plan
List<JMeterEngine> engines = new LinkedList<>();
Properties remoteProps = new Properties();
DistributedRunner distributedRunner = new DistributedRunner(
remoteProps);
List<String> hosts = new LinkedList<>();
// adding JMeter slaves here
hosts.add("172.16.104.199");
distributedRunner.setStdout(System.out);
distributedRunner.setStdErr(System.err);
distributedRunner.init(hosts, testPlanTree);
engines.addAll(distributedRunner.getEngines());
distributedRunner.start();
// jmeter.configure(testPlanTree);
// / jmeter.run();
System.err.println("Your Test excuted");
System.exit(0);
}
}
System.err.println("Jmeter properties error");
System.exit(1);
}
in console its showing
-Configuring remote engine: 172.16.104.199
Starting remote engines
Starting the test # Wed Jun 28 17:45:07 IST 2017 (1498652107364) Error in rconfigure() method java.rmi.UnmarshalException
I have tried to search it but didn't get any proper solution
It can happen if the jdk version on client is different than server
see in Post
I am addding custom headers to HTTPSampler programmatically while setting up JMeter test plan.
Please refer below snippet for the same:
HeaderManager headerManager = new HeaderManager();
headerManager.add(new Header("Foo", "Joe"));
sampler.setHeaderManager(headerManager);`
The problem here is that this custom header is not being sent to server.
Is there anything that I am missing here?
It won't work this way, you need to amend your code to add HeaderManager HashTree to HTTPSamplerProxy HashTree. After that you need to add this HTTPSamplerProxy to Thread Group, something like:
HashTree httpRequestTree = new HashTree();
httpRequestTree.add(httpRequest, manager);
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(httpRequestTree);
Full code, just in case:
// JMeter Test Plan, basically JOrphan HashTree
HashTree testPlanTree = new HashTree();
// Create Header Manager
HeaderManager manager = new HeaderManager();
manager.add(new Header("Foo", "Joe"));
manager.setName(JMeterUtils.getResString("header_manager_title")); // $NON-NLS-1$
manager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());
// HTTP Sampler - open example.com
HTTPSamplerProxy httpRequest = new HTTPSamplerProxy();
httpRequest.setDomain("example.com");
httpRequest.setPort(80);
httpRequest.setPath("/");
httpRequest.setMethod("GET");
httpRequest.setName("Open example.com");
httpRequest.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
httpRequest.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.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());
// HTTP Request Sampler and Header Manager
HashTree httpRequestTree = new HashTree();
httpRequestTree.add(httpRequest, manager);
// Construct Test Plan from previously initialized elements
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(httpRequestTree);
Check out Five Ways To Launch a JMeter Test without Using the JMeter GUI for more information on building JMeter Test Plan programatically.
I am attempting to convert a JMeter test plan I have into a pure Java implementation using the JMeter version 2.12 API but I am having no luck getting the test to execute successfully. The implementation I have is based off of the test plan .jmx file from the GUI test which does execute successfully when run through the GUI. The test I am trying to convert is a JMS Publisher sending one text message to an ActiveMQ broker on my localhost. I have confirmed that the message is received when executed through the JMeter GUI but I cannot achieve the same success with the Java implementation. The code compiles and runs, but I'm not sure why the JMS Publisher doesn't successfully send the message:
public static void main(String[] args) {
String jmeterLocation = "C:\\Users\\Andrew2\\Desktop\\apache-jmeter-2.12\\";
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//Load JMeter properties
JMeterUtils.loadJMeterProperties(jmeterLocation + "bin\\jmeter.properties");
JMeterUtils.setJMeterHome(jmeterLocation);
JMeterUtils.initLocale();
HashTree testPlanTree = new HashTree();
//Build Sampler
PublisherSampler jmsPublisher = new PublisherSampler();
jmsPublisher.setProperty("jms.jndi_properties", "false");
jmsPublisher.setProperty("jms.initial_context_factory","org.apache.activemq.jndi.ActiveMQInitialContextFactory");
jmsPublisher.setProperty("jms.provider_url","tcp://127.0.0.1:61616");
jmsPublisher.setProperty("jms.connection_factory","ConnectionFactory");
jmsPublisher.setProperty("jms.topic","dynamicQueues/NewQueue");
jmsPublisher.setProperty("jms.expiration","100");
jmsPublisher.setProperty("jms.priority","6");
jmsPublisher.setProperty("jms.security_principle","");
jmsPublisher.setProperty("jms.security_credentials","");
jmsPublisher.setProperty("jms.text_message","test..test..");
jmsPublisher.setProperty("jms.input_file","");
jmsPublisher.setProperty("jms.random_path","");
jmsPublisher.setProperty("jms.config_choice","jms_use_text");
jmsPublisher.setProperty("jms.config_msg_type","jms_text_message");
jmsPublisher.setProperty("jms.iterations","1");
jmsPublisher.setProperty("jms.authenticate",false);
JMSProperties jmsProperties = new JMSProperties();//set header property
jmsProperties.addJmsProperty(new JMSProperty("TestID","123456","java.lang.String"));
//Build Result Collector so that results can be inspected after test
ResultCollector rc = new ResultCollector();
rc.setEnabled(true);
rc.setErrorLogging(false);
rc.isSampleWanted(true);
SampleSaveConfiguration ssc = new SampleSaveConfiguration();
ssc.setTime(false);
ssc.setLatency(false);
ssc.setTimestamp(true);
ssc.setSuccess(true);
ssc.setLabel(false);
ssc.setCode(false);
ssc.setMessage(false);
ssc.setThreadName(false);
ssc.setDataType(false);
ssc.setEncoding(false);
ssc.setAssertions(false);
ssc.setSubresults(false);
ssc.setResponseData(false);
ssc.setSamplerData(false);
ssc.setAsXml(false);
ssc.setFieldNames(false);
ssc.setResponseHeaders(false);
ssc.setRequestHeaders(false);
ssc.setAssertionResultsFailureMessage(false);
ssc.setThreadCounts(false);
rc.setSaveConfig(ssc);
rc.setFilename("C:\\Users\\Andrew2\\Desktop\\constantthroughput-singleserver.csv");
//Create Loop Controller
LoopController loopController = new LoopController();
loopController.setEnabled(true);
loopController.setLoops(3);
loopController.addTestElement(jmsPublisher);
loopController.setFirst(true);
loopController.initialize();
//Create Thread Group
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setEnabled(true);
threadGroup.setNumThreads(1);
threadGroup.setRampUp(1);
threadGroup.setSamplerController(loopController);
//Create Test Plan
testPlanTree.add("testPlan",new TestPlan("JMeter JMS test"));
testPlanTree.add("loopController",loopController);
testPlanTree.add("JMS Publisher",jmsPublisher);
testPlanTree.add("Logger",rc);
testPlanTree.add("ThreadGroup",threadGroup);
//Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();
}
Based on the example JMeterFromScratch.java Dmitri listed above I have revised my code and now it works, the working code is:
public static void main(String[] args) throws FileNotFoundException, IOException {
String jmeterLocation = "C:\\Users\\Andrew2\\Desktop\\apache-jmeter-2.12\\";
StandardJMeterEngine jmeter = new StandardJMeterEngine();
//Load JMeter properties
JMeterUtils.loadJMeterProperties(jmeterLocation + "bin/jmeter.properties");
JMeterUtils.setJMeterHome(jmeterLocation);
JMeterUtils.initLocale();
HashTree testPlanTree = new HashTree();
//Build Sampler
PublisherSampler jmsPublisher = new PublisherSampler();
jmsPublisher.setProperty("jms.jndi_properties", "false");
jmsPublisher.setProperty("jms.initial_context_factory","org.apache.activemq.jndi.ActiveMQInitialContextFactory");
jmsPublisher.setProperty("jms.provider_url","tcp://127.0.0.1:61616");
jmsPublisher.setProperty("jms.connection_factory","ConnectionFactory");
jmsPublisher.setProperty("jms.topic","dynamicQueues/NewQueue");
jmsPublisher.setProperty("jms.expiration","100");
jmsPublisher.setProperty("jms.priority","6");
jmsPublisher.setProperty("jms.security_principle","");
jmsPublisher.setProperty("jms.security_credentials","");
jmsPublisher.setProperty("jms.text_message","test..test..");
jmsPublisher.setProperty("jms.input_file","");
jmsPublisher.setProperty("jms.random_path","");
jmsPublisher.setProperty("jms.config_choice","jms_use_text");
jmsPublisher.setProperty("jms.config_msg_type","jms_text_message");
jmsPublisher.setProperty("jms.iterations","1");
jmsPublisher.setProperty("jms.authenticate",false);
JMSProperties jmsProperties = new JMSProperties();//set header property
jmsProperties.addJmsProperty(new JMSProperty("TestID","123456","java.lang.String"));
//Build Result Collector so that results can be inspected after test
ResultCollector rc = new ResultCollector();
rc.setEnabled(true);
rc.setErrorLogging(false);
rc.isSampleWanted(true);
SampleSaveConfiguration ssc = new SampleSaveConfiguration();
ssc.setTime(false);
ssc.setLatency(false);
ssc.setTimestamp(true);
ssc.setSuccess(true);
ssc.setLabel(false);
ssc.setCode(false);
ssc.setMessage(false);
ssc.setThreadName(false);
ssc.setDataType(false);
ssc.setEncoding(false);
ssc.setAssertions(false);
ssc.setSubresults(false);
ssc.setResponseData(false);
ssc.setSamplerData(false);
ssc.setAsXml(false);
ssc.setFieldNames(false);
ssc.setResponseHeaders(false);
ssc.setRequestHeaders(false);
ssc.setAssertionResultsFailureMessage(false);
ssc.setThreadCounts(false);
rc.setSaveConfig(ssc);
rc.setFilename("C:\\Users\\Andrew2\\Desktop\\constantthroughput-singleserver.csv");
//Create Loop Controller
LoopController loopController = new LoopController();
loopController.setEnabled(true);
loopController.setLoops(1);
loopController.setFirst(true);
loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
loopController.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());
loopController.initialize();
//Create Thread Group
SetupThreadGroup threadGroup = new SetupThreadGroup();
threadGroup.setEnabled(true);
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());
//Create Test Plan
TestPlan testPlan = new TestPlan("New Test Plan");
testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());
//Load elements into test plan
testPlanTree.add(testPlan);
HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
threadGroupHashTree.add(jmsPublisher);
threadGroupHashTree.add(rc);
SaveService.saveTree(testPlanTree, new FileOutputStream(jmeterLocation + "bin/testjms.jmx"));
Summariser summer = null;
String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
if (summariserName.length() > 0) {
summer = new Summariser(summariserName);
}
//Run Test Plan
jmeter.configure(testPlanTree);
jmeter.run();
}
If you have a relevant .jmx file you can launch it programatically as per 4.2 Running an existing JMeter Test from Java code chapter of 5 Ways To Launch a JMeter Test without Using the JMeter GUI guide.
If you looking for a way of designing load test purely in Java, your code is missing some important bits like TestElement.TEST_CLASS property. Also ThreadGroup should be represented as HashTree.
See JMeterFromScratch.java source code for reference.
Hope this helps.