jmeter

JMeter: within JSR223 script get total number of samplers within a particular thread group


I have this JMeter test plan

JMeter test plan

How can get number of samplers within "Test 1 Thread Group" (3 in this particular example)?


Solution

  • Here is a full Java JSR223 sampler code to find out number of samplers in ThreadGroup with particular name:

    import org.apache.jmeter.save.SaveService;
    import org.apache.jmeter.services.FileServer;
    import java.io.File;
    import org.apache.jmeter.testelement.TestPlan;
    import org.apache.jmeter.threads.AbstractThreadGroup;
    import org.apache.jmeter.threads.ThreadGroup;
    import org.apache.jorphan.collections.HashTree;
    import org.apache.jorphan.collections.ListedHashTree;
    import org.apache.jorphan.collections.SearchByClass;
    import org.apache.jmeter.testelement.TestElement;
    import org.apache.jmeter.samplers.AbstractSampler;
    import org.apache.jmeter.control.GenericController;
    
    log.info("----------------------------------------------------");
    
    String basePath = FileServer.getFileServer().getBaseDir();
    String jmxFile = basePath + File.separator + "test.jmx";
    File file = new File(jmxFile);
    HashTree tree = SaveService.loadTree(file);
    
    static int getNumberOfSamplers(String threadGroupName) {
        for (Map.Entry entry : tree.entrySet()) {
            if (entry.getKey() instanceof TestPlan) {
                HashTree testplan = (HashTree) entry.getValue();
    
                for (Map.Entry element : testplan.entrySet()) {
                    if (element.getKey() instanceof AbstractThreadGroup) {
                        AbstractThreadGroup myGroup = (AbstractThreadGroup) element.getKey();
                        if (myGroup.getName().equals(threadGroupName)) {
                            SearchByClass samplerSearch = new SearchByClass(AbstractSampler.class);
                            element.getValue().traverse(samplerSearch); // element.getValue() is ListedHashTree
                            return samplerSearch.getSearchResults().size();
                        }
                    }
                }
            }
        }
        return 0;
    }
    log.info(getNumberOfSamplers("Test 1 Thread Group").toString());
    log.info(getNumberOfSamplers("Test 2 Thread Group").toString());
    
    
    log.info("----------------------------------------------------");