本文出自One Coder博客,转载请务必注明出处: http://www.coderli.com/archives/multi-thread-junit-grobountils/html
写过Junit单元测试的同窗应该会有感受,Junit自己是不支持普通的多线程测试的,这是由于Junit的底层实现上,是用System.exit退出用例执行的。JVM都终止了,在测试线程启动的其余线程天然也没法执行。JunitCore代码以下:java
- /**
- * Run the tests contained in the classes named in the <code>args</code>.
- * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
- * Write feedback while tests are running and write
- * stack traces for all failed tests after the tests all complete.
- * @param args names of classes in which to find tests to run
- */
- public static void main(String... args) {
- runMainAndExit(new RealSystem(), args);
- }
- /**
- * Do not use. Testing purposes only.
- * @param system
- */
- public static void runMainAndExit(JUnitSystem system, String... args) {
- Result result= new JUnitCore().runMain(system, args);
- system.exit(result.wasSuccessful() ? 0 : 1);
- }
RealSystem.java:web
- public void exit(int code) {
- System.exit(code);
- }
- <dependency>
- <groupId>net.sourceforge.groboutils</groupId>
- <artifactId>groboutils-core</artifactId>
- <version>5</version>
- </dependency>
Repository | Opensymphony Releases |
Repository url | https://oss.sonatype.org/content/repositories/opensymphony-releases |
- /**
- * 多线程测试用例
- *
- * @author lihzh(One Coder)
- * @date 2012-6-12 下午9:18:11
- * @blog http://www.coderli.com
- */
- @Test
- public void MultiRequestsTest() {
- // 构造一个Runner
- TestRunnable runner = new TestRunnable() {
- @Override
- public void runTest() throws Throwable {
- // 测试内容
- }
- };
- int runnerCount = 100;
- //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();
- }
- }
执行一下,看看效果。怎么样,你的Junit也能够执行多线程测试用例了吧:)。sql
本文出自One Coder博客,转载请务必注明出处: http://www.coderli.com/archives/multi-thread-junit-grobountils/数组