• Jmeter里的全能java测试sampler Java request


    Java request 难理解吗?其实很简单:

    jmeter 自带了两个

    org.apache.jmeter.protocol.java.test.JavaTest 

    JavaTest 的处理逻辑是固定的(可以通过查看源码来证实),就是 sleep 一下(默认100ms),然后响应,如果有设置,比如ResponseCode,那么按照设置的来响应,否则就不给响应,或者使用默认值:

    可以随便填写:

    Status 默认是ok, 如果不是ok,那么就会是 报错:

     

     

     和 org.apache.jmeter.protocol.java.test.SleepTest , 这个就更简单了, 略去。

    1 idea 中新建maven项目(最好是新建,否则导出的jar 会太大,不好看),然后项目中引入ApacheJMeter 的jar:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>testJmter</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>com.lk.anything</groupId>
                <artifactId>apacheJemter1</artifactId>
                <version>1</version>
                <scope>system</scope>
                <systemPath>D:/devTool/apache-jmeter-5.3/apache-jmeter-5.3/lib/ext/ApacheJMeter_java.jar</systemPath>
            </dependency>
            <dependency>
                <groupId>com.lk.anything</groupId>
                <artifactId>apacheJemter2</artifactId>
                <version>1</version>
                <scope>system</scope>
                <systemPath>D:/devTool/apache-jmeter-5.3/apache-jmeter-5.3/lib/ext/ApacheJMeter_core.jar</systemPath>
            </dependency>
            <dependency>
                <groupId>com.lk.anything</groupId>
                <artifactId>apacheJemter3</artifactId>
                <version>1</version>
                <scope>system</scope>
                <systemPath>D:/devTool/apache-jmeter-5.3/apache-jmeter-5.3/lib/jorphan.jar</systemPath>
            </dependency>
        </dependencies>
    </project>

    上面主要是3个ApacheJMeter 的jar, 缺一不可。

    创建自定义的JavaSamplerClient  继承于 AbstractJavaSamplerClient :

    package com.lk;
    
    import org.apache.jmeter.config.Arguments;
    import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
    import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
    import org.apache.jmeter.samplers.SampleResult;
    import org.apache.jorphan.logging.LoggingManager;
    import org.apache.log.Logger;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class TestOne extends AbstractJavaSamplerClient implements Serializable {
    
        private static final Logger LOG = LoggingManager.getLoggerForClass();
    
        private static final long serialVersionUID = 240L;
    //定义常量getDefaultParameters()使用
        private static final String Str1 = "Str1_Value";
        //自定义的参数
        private String str1;
    
        /**
         * Default constructor for <code>JavaTest</code>.
         *
         * The Java Sampler uses the default constructor to instantiate an instance
         * of the client class.
         */
        public TestOne() {
            LOG.debug(whoAmI() + "\tConstruct");
        }
    
    
        @Override
        public void setupTest(JavaSamplerContext context) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(whoAmI() + "\tsetupTest()");
            }
        }
    
    
        @Override
        public Arguments getDefaultParameters() {
            System.out.println("get Default Parameters +++++++++++++ ");
    
            Arguments params = new Arguments();
            //通过jmter的图形框进行传参,无默认值
            params.addArgument(Str1,"");
            params.addArgument("sleepTime","");
            params.addArgument("testVar","im a default value");
            return params;
        }
    
    
        @Override
        public SampleResult runTest(JavaSamplerContext context) {
            System.out.println("TestOne.runTest " + context);
    
            //通过传参给变量赋值
            str1 = context.getParameter(Str1);
            LOG.info(str1+"");
            SampleResult results = new SampleResult();
            //返回请求值,体现在jmeter查看结果数请求里面
            results.setSamplerData("请求参数"+str1);
    
            // Record sample start time.
            results.sampleStart();
            try {
                int sleepTime = context.getIntParameter("sleepTime");
                // Execute the sample. In this case sleep for the
                Thread.sleep(sleepTime);
    
                // specified time, if any
                //测试代码
                 List<String> arrList=new ArrayList<String>();
                 arrList.add(str1);
                 arrList.add("c");
                 arrList.add("d");
                 Iterator<String> iter=arrList.iterator();
                 while(iter.hasNext())
                 {
                     System.out.print(iter.next()+" ");
                     LOG.info(iter.next()+"");
    
                 }
                 results.setSuccessful(true);//这里决定测试用例成功还是失败
                 //返回结果
                 results.setResponseData("响应结果", null);
    
            } catch (Exception e) {
                LOG.warn("JavaTest: interrupted.");
                results.setSuccessful(true);
            } finally {
                // Record end time and populate the results.
                results.sampleEnd();
                //设置返回信息
                results.setResponseCode("200");
                results.setResponseMessage("成功测试");
                results.setSampleLabel("样式1");
    
    
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug(whoAmI() + "\trunTest()" + "\tTime:\t" + results.getTime());
            }
    
            return results;
        }
        private String whoAmI() {
            StringBuilder sb = new StringBuilder();
            sb.append(Thread.currentThread().toString());
            sb.append("@");
            sb.append(Integer.toHexString(hashCode()));
            System.out.println("whoAmI = " + sb);
            return sb.toString();
        }
    
    
    }
    View Code

    其中参数可以按照自己的需要随便设置, 还可以设置默认值,如:

    记得修改encoding,因为默认是 GBK,否则在jmeter gui 会有乱码:

    mvn clean packege,然后把它放置到 jmeter 的lib/ext 目录:

     重新启动 jmeter,(必须要重启,否则,读取不到),然后新建 Java请求,就可以选择到刚刚自定义的 TestOne: 

    注意,如果有修改TestOne, 那么重新替换 jmeter 的lib/ext 目录的同名jar 不起作用,必须要重启jmeter,而且呢,因为jmeter 会记住之前的填充的值, 也就是说jmter 有缓存,那么需要重新选择TestOne, 也就是先现在其他的 Java请求实现,然后再选择回来 TestOne ;

    参考

    https://blog.csdn.net/g695144224/article/details/50994524

    https://blog.csdn.net/qilinxo/article/details/81209523?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link


    版权声明
    本文原创发表于 博客园,作者为 阿K .     本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。
    欢迎关注本人微信公众号:觉醒的码农,或者扫码进群:

  • 相关阅读:
    DragonBones软件使用笔记 (pos工具、IK约束、关键帧等)
    【微信小游戏】CocosCreator 分包
    CocosCreator Shader笔记 (TheBookOfShader、渐变色、攻击闪白特效)
    【插件】cocos inspctor试用
    【微信小游戏】CocosCreator 微信小游戏排行榜
    [已解决]报错:The server time zone value '???ú±ê×??±??' is unrecognized or represents more than one time zone.
    Crontab 定时执行脚本配置
    【GIS】Mapbox、GeoServer矢量瓦片
    【PostGIS】实时坐标-电子围栏-判断-(参考遥想公瑾当年postgres+socket.io+nodejs实时地图应用实践)
    【MinIO】大文件上传配置
  • 原文地址:https://www.cnblogs.com/FlyAway2013/p/15547807.html
Copyright © 2020-2023  润新知