Junit spring 多線程測試

來源:互聯網
上載者:User

本文出自One Coder部落格,轉載請務必註明出處: http://www.coderli.com/archives/multi-thread-junit-grobountils/

寫過Junit單元測試的同學應該會有感覺,Junit本身是不支援普通的多線程測試的,這是因為Junit的底層實現上,是用System.exit退出用例執行的。JVM都終止了,在測試線程啟動的其他線程自然也無法執行。JunitCore代碼如下:

 /**       * 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);        }  

所以要想編寫多線程Junit測試案例,就必須讓主線程等待所有子線程執行完成後再退出。想到的辦法自然是Thread中的join方法。話又說回來,這樣一個簡單而又典型的需求,難道會沒有第三方的包支援麼。通過google,筆者很快就找到了GroboUtils這個Junit多線程測試的開源的第三方的工具包。    GroboUtils官網如下:   http://groboutils.sourceforge.net/   下載頁面: http://groboutils.sourceforge.net/downloads.html   Maven依賴方式:  

 <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
依賴好Jar包後就可以編寫多線程測試案例了。上手很簡單:
 /**       * 多線程測試案例       *        * @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 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.