使Junit能夠測試多線程的插件:groboutils

maven依賴:spring

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

注:若是下載失敗,則能夠選擇手動添加
	1)手動下載依賴的地址:https://oss.sonatype.org/content/repositories/opensymphony-releases/net/sourceforge/groboutils/groboutils-core/5/
	2)將下載的jar包放到: repository\net\sourceforge\groboutils\groboutils-core\5

舉例:數組

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
import net.sourceforge.groboutils.junit.v1.TestRunnable;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-test.xml")
public class JunitMultiThreadPluginDemo {
	

	[@Test](https://my.oschina.net/azibug)
	public void testThreadJunit() throws Throwable {   
		// 線程數組,模擬併發
		TestRunnable[] testThreadArray = new TestRunnable[10];  
		for(int i=0; i<testThreadArray.length; i++){  
			testThreadArray[i]=new MultiThreadTest();  
		}  

		// 執行多線程測試用例的Runner
		MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(testThreadArray);  
		
		// 併發執行
		mttr.runTestRunnables();  
		
	}  

	/**
	 * TestRunnable:表示一個測試線程的抽象類,子類須要實現該類的runTest()方法,在該方法中實現本身的測試代碼
	 */
	private class MultiThreadTest extends TestRunnable {

		[@Override](https://my.oschina.net/u/1162528)
		public void runTest() throws Throwable {	
			 // 在runTest()方法中實現 Thread.run() 中的內容
			execute();
		}
	}
	
	public void execute() {
	
		// 業務邏輯
		System.out.println("在這裏完成業務邏輯的相關代碼。。");
		
		try {
			Thread.sleep(10000); // 模擬相關代碼的執行
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
相關文章
相關標籤/搜索