Java Web 并发单元测试(2)

来源:互联网 发布:php框架排名 编辑:程序博客网 时间:2024/05/20 13:19

 使用GroboUtils进行简单并发单元测试,实现测试和监控和单个线程执行的控制,这里展示简单案例的测试过程:

1、建立要测试的线程TestRunnable1

/** *  */package com.dtsz.groboTest;import net.sourceforge.groboutils.junit.v1.TestRunnable;/** * @author xiaoli * */public class TestRunnable1 extends TestRunnable {private int i;private long sleepTime;public TestRunnable1(int i ,long sleepTime) {super();this.i = i;this.sleepTime = sleepTime;}/* (non-Javadoc) * @see net.sourceforge.groboutils.junit.v1.TestRunnable#runTest() */@Overridepublic void runTest() throws Throwable {// TODO Auto-generated method stubSystem.out.println(i+"线程正在跑…………");this.delay(sleepTime);System.out.println(i+"线程正要走完…………");}}

2、建立监控的线程,每个监控对应一个线程,也可以一个监控监控整个测试过程,需要传入监控的线程对象。

/** *  */package com.dtsz.groboTest;import net.sourceforge.groboutils.junit.v1.TestMonitorRunnable;import net.sourceforge.groboutils.junit.v1.TestRunnable;/** * @author xiaoli * */public class TestMonitorRunnable1 extends TestMonitorRunnable {private int i;private TestRunnable t;public TestMonitorRunnable1(int i,TestRunnable t) {super();this.i = i;this.t = t;}/* (non-Javadoc) * @see net.sourceforge.groboutils.junit.v1.TestMonitorRunnable#runMonitor() */@Overridepublic void runMonitor() throws Throwable {System.out.println(i+"线程监控正在跑…………状态:"+t.isDone());}}

3、建立主测试类进行并发单元测试,这里只有简单数据打印,具体情况传入数据进行测试,比如Web项目中需要在setUp()中部署好相关的环境等:

/** *  */package com.dtsz.groboTest;import junit.framework.TestCase;import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;import net.sourceforge.groboutils.junit.v1.TestMonitorRunnable;import net.sourceforge.groboutils.junit.v1.TestRunnable;import org.junit.Test;/** * @author xiaoli * */public class MainTest1 extends TestCase{@Overrideprotected void setUp() throws Exception {// TODO Auto-generated method stubsuper.setUp();System.out.println("setUp()数据准备"); }@Overrideprotected void tearDown() throws Exception {// TODO Auto-generated method stubsuper.tearDown();System.out.println("tearDown()结束"); }@Testpublic void test1() throws Throwable {int count = 2;long time = 0;TestRunnable[] tr = new TestRunnable[count];TestMonitorRunnable [] trm = new TestMonitorRunnable[count];for(int i = 0;i<count;i++) {TestRunnable1 t = new TestRunnable1(i,(i+1)*time);TestMonitorRunnable1 m = new TestMonitorRunnable1(i,t);tr[i] = t;trm[i] = m;}MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(tr,trm);//没有在该时间内完成的线程将会被杀掉mttr.runTestRunnables();}}

测试结果:监控器每隔几个毫秒会进行实时运行,知道整个单元测试结束:

setUp()数据准备
1线程监控正在跑…………状态:false
0线程监控正在跑…………状态:false
0线程正在跑…………
1线程正在跑…………
1线程监控正在跑…………状态:false
0线程监控正在跑…………状态:false
0线程正要走完…………
1线程正要走完…………
1线程监控正在跑…………状态:false
0线程监控正在跑…………状态:false
1线程监控正在跑…………状态:false
0线程监控正在跑…………状态:false
1线程监控正在跑…………状态:false
0线程监控正在跑…………状态:false
1线程监控正在跑…………状态:false
0线程监控正在跑…………状态:true
1线程监控正在跑…………状态:true
tearDown()结束


具体功能可以由这个引申出来。

原创粉丝点击