JMeter压测时如何在达到给定错误数量后停止测试

问题

在做接口自动性能测试时,偶尔会有不稳定的因素导致请求断言失败。JMeter线程组错误处理有两种常用处理方式:继续或停止测试

image-20220507110932343

因某些原因极个别错误不影响压测结果是可以忽略的,若选择继续测试,当真正发生服务崩溃时也会一直压下去这不是我们想要的,那么在压测过程中怎样才能在达到指定的累计错误数量后停止测试呢?

解决方

大致思路:使用beanshell脚本在每次请求结束后使用变量count记录错误数,达到预定的错误数量后通过ctx调用stoptest()结束测试。

  1. setUp Thread Group中添加一个BeanShell Sampler

    image-20220507113449876

  2. 给测试计划添加BeanShell Listener

    image-20220507113632198

  3. 执行测试

    image-20220507115518016

    以上使用httpbin提供的的接口进行测试,请求地址不存在的/error,所以在累计错误数count=5时测试停止。

  4. BeanShell Code

    // BeanShell Sampler
    props.put("__count", "0");
    
    // BeanShell Listener
    int __count = Integer.parseInt(props.get("__count"));
    int __limit = 5;
    int responseCode;
    
    try {
      responseCode = Integer.parseInt(prev.getResponseCode());
    }
    catch (exception ex) {
      responseCode = 0;
    }
    
    //log.warn("------" + prev.getFirstAssertionFailureMessage());
    boolean errorResponse = ((responseCode < 200) || (responseCode >= 400) || (prev.getErrorCount() > 0) || (prev.getFirstAssertionFailureMessage() != null));
    
    if (errorResponse) {
      __count = __count + 1;
    }
    log.warn( "errors = " + __count );
    
    if (__count >= __limit) {
    log.warn("maximum number of errors reached, aborting test.");
      ctx.getEngine().stoptest();
    }
    
    props.put("__count", String.valueOf(__count));
    

讨论

在整体解决过程中,用到了JMeter的一些特性:

  1. props设置count变量时只初始化一次,后面做累计操作,这里用了setUp Group;
  2. 为什么使用BeanShell Listener:在errorResponse的判断条件中有响应code、错误数量以及断言信息,这些只有在断言完成后才能获取到,按照JMeter组件执行顺序,Listener组件符合使用条件;

相关文章

Jmeter:Authenticationcredentialswerenotprovided上次在使...
初次使用jmeter时,结果树中返回的数据为未转码内容,如下:...
jmeter默认语言设置: 1、临时设置:进入options--ChooseLa...
第一步:打开jmeter工具。 第二步:点击鼠标右击,点击添加...
在之前的博文中,Jmeter二次开发——基于Java请求,已介绍了...
打开虚拟机然后用远程连接工具SSH连接到数据库将serveragent...