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组件符合使用条件;

posted @ 2022-05-08 09:48  。超人不会飞  阅读(383)  评论(0编辑  收藏  举报