SSH框架學習(八、Junit+GroboUtils進行多線程測試)

原文轉載:http://blog.csdn.net/wuyt2008/article/details/8275125

Junit4不能模擬多線程的情況,需要其他支持,我用的是GroboUtils,最新版本5,下載地址:http://groboutils.sourceforge.net/downloads.html


GroboUtils測試的代碼是用網上抄來的,來源:http://www.coderli.com/multi-thread-junit-grobountils

UserDAOImplTest的代碼

[java] view plaincopy
  1. package demo.myssh.dao.impl;  
  2.   
  3. import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;  
  4. import net.sourceforge.groboutils.junit.v1.TestRunnable;  
  5. import org.junit.Before;  
  6. import org.junit.Test;  
  7. import org.junit.runner.RunWith;  
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.beans.factory.annotation.Qualifier;  
  10. import org.springframework.test.annotation.Repeat;  
  11. import org.springframework.test.context.ContextConfiguration;  
  12. import org.springframework.test.context.junit4.*;  
  13. import demo.myssh.dao.IUserDAO;  
  14. import demo.myssh.model.User;  
  15.   
  16. @RunWith(SpringJUnit4ClassRunner.class)  
  17. @ContextConfiguration({ "file:WebRoot/WEB-INF/applicationContext.xml" })  
  18. public class UserDAOImplTest {  
  19.   
  20.     @Autowired  
  21.     @Qualifier("iUserDAO")  
  22.     private IUserDAO userDao;  
  23.   
  24.     @Test  
  25.     @Repeat(2)  
  26.     public void MultiRequestsTest() {  
  27.         // 構造一個Runner  
  28.         TestRunnable runner = new TestRunnable() {  
  29.             @Override  
  30.             public void runTest() throws Throwable {  
  31.                 // 測試內容  
  32.                 // System.out.println("a");  
  33.                 userDao.save(new User("aa""bb""cc"));  
  34.             }  
  35.         };  
  36.         int runnerCount = 2;  
  37.         // Rnner數組,相當於併發多少個。  
  38.         TestRunnable[] trs = new TestRunnable[runnerCount];  
  39.         for (int i = 0; i < runnerCount; i++) {  
  40.             trs[i] = runner;  
  41.         }  
  42.         // 用於執行多線程測試用例的Runner,將前面定義的單個Runner組成的數組傳入  
  43.         MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);  
  44.         try {  
  45.             // 開發併發執行數組裏定義的內容  
  46.             mttr.runTestRunnables();  
  47.         } catch (Throwable e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章