写并发测试用例的时候不要用JUnit,它不支持并发,将测试函数写在public static void main(String[] args)中。但如果一个测试类里有多个并发测试case的时候这招就不灵了,需要用testng解决这个问题。在Eclipse中使用TestNG需要首先安装testng for eclispe的plugin(见[1]),然后引用testng的jar包。然后就可以写测试用例了。
testng声明并发测试很简单,示例如下(改自[3]):
import org.testng.annotations.Test; @Test(invocationCount = 5, threadPoolSize = 3) public void testThreadPool() { System.out.println("Thread: " + Thread.currentThread().getId()); } 参数含义:(引自[2])
invocationCount: The number of times this method should be invoked.(线程体总共被执行多少次); threadPoolSize: The size of the thread pool for this method. The method will be invoked from multiple threads as specified by invocationCount.(线程池的大小,也就是并发的线程数目是多少) Note: this attribute is ignored if invocationCount is not specified 上面这个例子输出可能如下: Thread: 14 Thread: 13 Thread: 15 Thread: 14 Thread: 13 即程序共运行5次,共有3个线程。
[1] http://testng.org/doc/download.html
[2] http://testng.org/doc/documentation-main.html
[3] http://hi.baidu.com/sunshine/blog/item/9d355982cb1200a40cf4d2c9.html
http://www.raptorconsultants.com/uncategorized/testng-junit/