JMeter -基于平均响应时间的测试失败

omjgkv6w  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(184)

我正在Jenkins中使用性能插件运行一个JMeter作业。如果平均响应时间〈3秒,我需要使作业失败。我在jmeter中看到了“持续时间Assert”,但它在每个线程(每个http请求)上都有效。相反,是否可以对每个页面平均进行持续时间Assert?
这是我尝试添加BeanSehll侦听器和Assert的方法。

Recording Controller
     **Home Page**
         BeanShell Listener
         Debug Sampler
     **Page1**
         BeanShell Listener
         Debug Sampler
Beanshell Assertion
View Results Tree
pw136qt2

pw136qt21#

您可以通过某种形式的Beanshell脚本实现此检查
1.在与所有请求处于活动状态的级别相同的级别添加Beanshell监听器
1.将以下代码放入Beanshell监听器的“脚本”区域

String requests = vars.get("requests");
String times = vars.get("times");
long requestsSum = 0;
long timesSum = 0;

if (requests != null && times != null) {
    log.info("requests: " + requests);
    requestsSum = Long.parseLong(vars.get("requests"));
    timesSum = Long.parseLong(vars.get("times"));
}

long thisRequest = sampleResult.getTime();
timesSum += thisRequest;
requestsSum++;

vars.put("requests", String.valueOf(requestsSum));
vars.put("times", String.valueOf(timesSum));

long average = timesSum / requestsSum;

if (average > 3000){
    sampleResult.setSuccessful(false);
    sampleResult.setResponseMessage("Average response time is greater than threshold");
}

上面的代码将每个请求的响应时间总和和请求总数记录到timesrequestsJMeter Variables
有关Apache JMeter中Beanshell脚本的全面信息,请参见How to use BeanShell: JMeter's favorite built-in component指南。

k0pti3hp

k0pti3hp2#

根据另一个答案,我设法创建了一个在使用多线程时工作的东西。
将下面的代码作为脚本添加到JSR223侦听器中,您还可以将其保存到文件中并从文件中加载它(以便于重用)。

import org.apache.jmeter.util.JMeterUtils;

int totalRequests = Integer.parseInt(ctx.getThreadGroup().getSamplerController().getProperty("LoopController.loops").getStringValue()) * ctx.getThreadGroup().getNumThreads();
long requestsCount = JMeterUtils.getPropDefault("requestsCount"+sampleResult.toString(),0);
long timesSum = JMeterUtils.getPropDefault("times"+sampleResult.toString(),0);

long thisRequestTime = sampleResult.getTime();
timesSum += thisRequestTime;
requestsCount++;

JMeterUtils.setProperty("requestsCount"+sampleResult.toString(), String.valueOf(requestsCount));
JMeterUtils.setProperty("times"+sampleResult.toString(), String.valueOf(timesSum));

long average = timesSum / requestsCount;

long threshold = Integer.parseInt(args[0])*1000;
if (requestsCount >= totalRequests) {
    if(average > threshold){
        sampleResult.setSuccessful(false);
        sampleResult.setResponseMessage("Average response time is greater than threshold, average: " + String.valueOf(average) + ", threshold: " + threshold);
    }
    log.info("Average response time (" + sampleResult.toString() + "): " + String.valueOf(average) + ", threshold: " + threshold);
}

这将把它存储在全局属性中,这些属性是为完整的JVM运行而保存的。

import org.apache.jmeter.util.JMeterUtils;
JMeterUtils.getJMeterProperties().clear();
log.info("cleared properties");

相关问题