动态设置用户定义的变量

时间:2018-10-19 01:02:40

标签: java jmeter jmeter-plugins

在启动测试期间,是否可以使用Java在jmx文件中动态设置用户定义的变量?

到目前为止,我可以使用以下代码来打印名称:

 try {

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

            // Initialize Properties, logging, locale, etc.
            JMeterUtils.loadJMeterProperties("c:\\path\\jmeter.properties");
            JMeterUtils.setJMeterHome("C:\\path\\apache-jmeter-5.0");
            JMeterUtils.initLocale();

            // Initialize JMeter SaveService
            SaveService.loadProperties();

            // Load existing .jmx Test Plan
            Path path = Paths.get("C:\\path\\whatever.jmx");
            HashTree testPlanTree = SaveService.loadTree(path.toFile());

            // Run JMeter Test
            jmeter.configure(testPlanTree);

            JMeterTreeModel treeModel = new JMeterTreeModel();
            JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
            treeModel.addSubTree(testPlanTree, root);

            SearchByClass<TestPlan> testPlan = new SearchByClass<>(TestPlan.class);
            testPlanTree.traverse(testPlan);
            Collection<TestPlan> testPlans = testPlan.getSearchResults();
            for (TestPlan testPlan1 : testPlans) {
                System.out.println(testPlan1.getName());

                JMeterProperty udvProperty = testPlan1.getUserDefinedVariablesAsProperty();

                Arguments arg = (Arguments) udvProperty.getObjectValue();

                CollectionProperty arguments = arg.getArguments();

                arguments.forEach(c -> {

                    System.out.println(c);

                });

            }

            // jmeter.run();

        }
        catch (IOException | IllegalUserActionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

我快到了!但是只需要一些建议,这是否是正确的方向?还是有另一种更好的方法?

更新: 我可以通过修改上面的代码来设置变量:

try {

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

            // Initialize Properties, logging, locale, etc.
            JMeterUtils.loadJMeterProperties("c:\\path\\jmeter.properties");
            JMeterUtils.setJMeterHome("C:\\path\\apache-jmeter-5.0");
            JMeterUtils.initLocale();

            // Initialize JMeter SaveService
            SaveService.loadProperties();

            // Load existing .jmx Test Plan
            Path path = Paths.get("C:\\path\\whatever.jmx");
            HashTree testPlanTree = SaveService.loadTree(path.toFile());

            // Run JMeter Test
            jmeter.configure(testPlanTree);

            JMeterTreeModel treeModel = new JMeterTreeModel();
            JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot();
            treeModel.addSubTree(testPlanTree, root);

            SearchByClass<TestPlan> testPlan = new SearchByClass<>(TestPlan.class);
            testPlanTree.traverse(testPlan);
            Collection<TestPlan> testPlans = testPlan.getSearchResults();
            for (TestPlan testPlan1 : testPlans) {
                System.out.println(testPlan1.getName());

                JMeterProperty udvProperty = testPlan1.getUserDefinedVariablesAsProperty();

                Arguments arg = (Arguments) udvProperty.getObjectValue();

                CollectionProperty arguments = arg.getArguments();

                arguments.forEach(c -> {

                Argument j = (Argument) c.getObjectValue();
                System.out.println("-----j--- " + j.getName());
                j.setValue("whatever value");

                System.out.println(j);

                });

            }

            // jmeter.run();

        }
        catch (IOException | IllegalUserActionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:1)

用户定义的变量测试元素由org.apache.jmeter.config.Arguments类表示,因此直接查找Arguments是有意义的,因为它将更加方便,快速和易读。

addArgument()函数可用于添加用户定义的变量

例如,此代码将从定义的位置读取测试计划,添加一个值为foo的用户定义变量bar,然后将测试计划保存回去

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

// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties("c:\\path\\jmeter.properties");
JMeterUtils.setJMeterHome("C:\\path\\apache-jmeter-5.0");
JMeterUtils.initLocale();

// Initialize JMeter SaveService
SaveService.loadProperties();

// Load existing .jmx Test Plan
Path path = Paths.get("C:\\path\\whatever.jmx");
HashTree testPlanTree = SaveService.loadTree(path.toFile());

SearchByClass<Arguments> udvSearch = new SearchByClass<>(Arguments.class);
testPlanTree.traverse(udvSearch);
Collection<Arguments> udvs = udvSearch.getSearchResults();

Arguments userDefinedVariables = udvs.stream().findAny().get();

System.out.println("Current values:");

userDefinedVariables.getArgumentsAsMap().forEach((k, v) -> System.out.println("Name : " + k + " Value : " + v));

userDefinedVariables.addArgument("foo", "bar");

SaveService.saveTree(testPlanTree, new FileOutputStream("C:\\path\\whatever.jmx"));

请查看Five Ways To Launch a JMeter Test without Using the JMeter GUI,以获取有关创建JMeter测试计划的不同方式的更多信息(包括运行现有测试和使用JMeter API创建全新的测试)

答案 1 :(得分:0)

经过仔细研究,我想出了这个代码片段。我已经在 J​​Meter 5.3 及更高版本上测试过它,它对我有用。它看起来与其他答案相似,但我已经仔细解释了每一行中发生的事情。希望这会有所帮助。

// Initialize Properties, logging, locale, etc.
JMeterUtils.loadJMeterProperties("apache-jmeter-5.3/bin/jmeter.properties");
JMeterUtils.setJMeterHome("apache-jmeter-5.3"); // Have the apache JMeter extracted in the same folder
JMeterUtils.initLocale();

try {
    // Initialize JMeter SaveService
    SaveService.loadProperties();
} catch (IOException e) {
    // handle the error
}

// add user defined variables
HashMap<String, String> userArguments = new HashMap<>();
userArguments.put("variable1", "value1");
userArguments.put("variable2", "value2");
userArguments.put("variable3", "value3");

String jmxFilePath = "jmeterscript.jmx";
File jmxFile = new File(jmxFilePath);

// get the jmeter to run by configuring it
StandardJMeterEngine jMeterEngine = configureJmeterEngine(jmxFile, userArguments);

// starting to invoke the JMeter Script
jMeterEngine.run();
jMeterEngine.reset();
jMeterEngine.exit();

/**
 * This method returns a configured StandardJMeterEngine based on a arguments configured in
 * a JMX file and arguments defined by user through metadata
 *
 * @param jmxFileName JMX file path
 * @param arguments   User defined arguments
 * @return Configured StandardJMeterEngine
 */
private StandardJMeterEngine configureJmeterEngine(File jmxFileName, HashMap<String, String> arguments) {
    StandardJMeterEngine standardJMeterEngine = new StandardJMeterEngine();
    try {
        // Get test plan tree
        HashTree testPlanTree = SaveService.loadTree(jmxFileName);
        // Get all user defined arguments in JMX file
        SearchByClass<Arguments> udvSearch = new SearchByClass<>(Arguments.class);
        testPlanTree.traverse(udvSearch);
        Collection<Arguments> udvs = udvSearch.getSearchResults();
        Arguments args = udvs.stream().findAny().orElseGet(Arguments::new);
        // Add user defined arguments in metadata
        arguments.keySet().forEach(key -> args.addArgument(key, arguments.get(key)));
        // Configure JMeter engine
        standardJMeterEngine.configure(testPlanTree);
    } catch (Exception e) {
        logger.error("Error in configuring a Jmeter Probe", e);
    }
    return standardJMeterEngine;
}