性能测试工具 Junit4+MultiThreadedTestRunner 并发测试

会飞的猪 · 2017年08月01日 · 1353 次阅读

最近要对一个类里的方法,进行压力测试。下面讲一下写出的 Junit4 的并发测试代码吧。如果要复用的话,只需要改下运行时间,要并发的代码就可以了。
具体步骤:
1、新建一个 maven 项目。(因为要引入很多公司的包,所以要使用 pom.xml 来管理 jar 包)
主要引入的包有以下三个 1.被测方法所在的 jar 包 2.Junit4 的包 3.GroboUtils 这个 Junit 多线程测试的开源的第三方的工具包
pom.xml 里包含的内容

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    <dependency> 
          <groupId>net.sourceforge.groboutils</groupId> 
          <artifactId>groboutils-core</artifactId> 
          <version>5</version> 
        </dependency> 

2、具体代码如下 所示

package com.test.mq;

import static org.junit.Assert.*;

import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
import net.sourceforge.groboutils.junit.v1.TestRunnable;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

public class test {
    // 用来并发计数 调了多少次方法
    private static int num;
    private static AtomicInteger count = new AtomicInteger();

    @Test
    public void testExpression() {
        TestRunnable runner = new TestRunnable() {

            @Override
            public void runTest() throws Throwable {
                // TODO Auto-generated method stub
                // 存放并发的代码
                increment();
                num = getCount();
                System.out.println(num);
            }
        };
        // runnerCount 并发数 100
        // time 并发时间 单位秒
        int time = 10;
        int runnerCount = 100;
        TestRunnable[] trs = new TestRunnable[runnerCount];
        for (int i = 0; i < runnerCount; i++) {
            trs[i] = runner;
        }

        MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
        try {

            long startTime = System.currentTimeMillis();
            while (true) {
                long endTime = System.currentTimeMillis();
                mttr.runTestRunnables();
                // 并发运行 放在while死循环里 当时间到了,跳出循环

                if ((endTime - startTime) > time*1000) {
                    System.out.println(num);
                    break;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

    public void increment() {
        count.incrementAndGet();
    }

    public int getCount() {
        return count.get();
    }

}

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册