This article from one Coder blog, reproduced Please be sure to indicate the source: http://www.coderli.com/archives/multi-thread-junit-grobountils/
Students who have written JUnit unit tests should have a feeling that JUnit itself does not support common multithreaded testing, because the underlying implementation of JUnit is to use System.exit to exit the use case execution. The JVM is terminated, and other threads that are started by the test thread are naturally unable to execute. The Junitcore code is as follows:
/** * 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:
public void exit (int code) {System.exit (code); }
So to write multithreaded JUnit test cases, you must have the main thread wait for all child threads to complete and then exit. The idea is naturally the join method in thread. Then again, such a simple and typical demand, there will be no Third-party package support. Through Google, the author quickly found the groboutils of this junit multithreaded test of the open source of the Third-party Toolkit. Groboutils official website is as follows: http://groboutils.sourceforge.net/download page: http://groboutils.sourceforge.net/downloads.html How MAVEN relies:
<dependency> <groupId>net.sourceforge.groboutils</groupId> <artifactid>groboutils-co Re</artifactid> <version>5</version> </dependency>
Note: Third party library support required:
Repository |
Opensymphony releases |
Repository URL |
Https://oss.sonatype.org/content/repositories/opensymphony-releases |
You can write multithreaded test cases after you rely on a good jar package. The start is simple:
/** * Multithreading test cases * * @author lihzh (one coder) * @ date 2012-6-12 afternoon 9:18:11 * @blog http://www.coderli.com */ @Test public void multirequeststest () { // construct a runner Testrunnable runner = new testrunnable () { @Override