Java Web 并發單元測試(2)
使用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() */ @Override public void runTest() throws Throwable { // TODO Auto-generated method stub System.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() */ @Override public 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{ @Override protected void setUp() throws Exception { // TODO Auto-generated method stub super.setUp(); System.out.println("setUp()數據準備"); } @Override protected void tearDown() throws Exception { // TODO Auto-generated method stub super.tearDown(); System.out.println("tearDown()結束"); } @Test public 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()結束
具體功能可以由這個引申出來。
相關文章:
posted on 2013-12-09 10:40 順其自然EVO 閱讀(287) 評論(0) 編輯 收藏 所屬分類: web 前端性能測試