原文轉載: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的代碼
- package demo.myssh.dao.impl;
- import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
- import net.sourceforge.groboutils.junit.v1.TestRunnable;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Qualifier;
- import org.springframework.test.annotation.Repeat;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.*;
- import demo.myssh.dao.IUserDAO;
- import demo.myssh.model.User;
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration({ "file:WebRoot/WEB-INF/applicationContext.xml" })
- public class UserDAOImplTest {
- @Autowired
- @Qualifier("iUserDAO")
- private IUserDAO userDao;
- @Test
- @Repeat(2)
- public void MultiRequestsTest() {
- // 構造一個Runner
- TestRunnable runner = new TestRunnable() {
- @Override
- public void runTest() throws Throwable {
- // 測試內容
- // System.out.println("a");
- userDao.save(new User("aa", "bb", "cc"));
- }
- };
- int runnerCount = 2;
- // Rnner數組,相當於併發多少個。
- TestRunnable[] trs = new TestRunnable[runnerCount];
- for (int i = 0; i < runnerCount; i++) {
- trs[i] = runner;
- }
- // 用於執行多線程測試用例的Runner,將前面定義的單個Runner組成的數組傳入
- MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
- try {
- // 開發併發執行數組裏定義的內容
- mttr.runTestRunnables();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }
- }