Skip to main content
change tags
Link
walsh
  • 3.3k
  • 2
  • 19
  • 32
Source Link
walsh
  • 3.3k
  • 2
  • 19
  • 32

Why is the JMeter SampleListener not executing?

I am using the JMeter SDK to construct a test, and below is the complete code. In this code, there is a collector object that implements SampleListener. After the test execution is completed, I intend to use this collector to perform some assertions. However, the target API was successfully executed, but the methods of the collector object were not executed at all. Could you please explain why this is happening?

@Test
public void testListUserPerf() throws IOException {
  var jmeterHome = new File("D:\\Tools\\apache-jmeter-5.6.3");
  var slash = FileSystems.getDefault().getSeparator();
  var jmeterProperties = jmeterHome + slash + "bin" + slash + "jmeter.properties";
  JMeterUtils.loadJMeterProperties(jmeterProperties);
  JMeterUtils.setJMeterHome(jmeterHome.getPath());
  JMeterUtils.initLocale();

  var testPlan = new TestPlan("JMeter SDK Test Plan");

  var loopController = new LoopController();
  loopController.setLoops(1);
  loopController.setFirst(true);
  loopController.initialize();

  var threadGroup = new org.apache.jmeter.threads.ThreadGroup();
  threadGroup.setNumThreads(100);
  threadGroup.setRampUp(1);
  threadGroup.setSamplerController(loopController);

  HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();
  httpSampler.setDomain("localhost");
  httpSampler.setPort(8080);
  httpSampler.setPath("/users");
  httpSampler.setMethod("GET");

  var assertion = new ResponseAssertion();
  assertion.setTestFieldResponseCode();
  assertion.setToEqualsType();
  assertion.addTestString("400");
  assertion.setAssumeSuccess(false);

  var collector = new SampleListener() {
  final List<SampleResult> results = new ArrayList<>();
    @Override
    public void sampleOccurred(SampleEvent e) {
      results.add(e.getResult());
    }

    @Override
    public void sampleStarted(SampleEvent e) {
    }

    @Override
    public void sampleStopped(SampleEvent e) {
    }
  };

  var samplerTree = new HashTree();
  samplerTree.add(httpSampler);
  samplerTree.add(assertion);

  var testPlanTree = new HashTree();
  testPlanTree.add(testPlan);
  var threadGroupSubTree = testPlanTree.add(testPlan, threadGroup);
  threadGroupSubTree.add(samplerTree);
  testPlanTree.add(testPlan, collector);

  var jmeter = new StandardJMeterEngine();
  jmeter.configure(testPlanTree);
  jmeter.run();

  for (var result : collector.results) {
    assertTrue(result.isSuccessful());
  }

  assertEquals(100, collector.results.size(), "results.size should be 100");
}