JUnit4中的測試套件
測試套件
JUnit3.8中,用測試套件同時運行多個測試類(http://www.cnblogs.com/mengdd/archive/2013/04/07/3006265.html)。
在JUnit4中也有類似功能,只不過是用注解來實現的。
Suite類的文檔
public class Suite
extends org.junit.internal.runners.CompositeRunnerUsing
Suite as a runner allows you to manually build a suite containing tests from many classes.
It is the JUnit 4 equivalent of the JUnit 3.8.x static Test suite() method.
To use it, annotate a class with @RunWith(Suite.class) and @SuiteClasses(TestClass1.class, ...).
When you run this class, it will run all the tests in all the suite classes.
程序實例
寫一個類TestAll,然后讓其運行CalculatorTest和ParametersTest中的測試:
package com.mengdd.junit4; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) // 指定運行器 @Suite.SuiteClasses({ CalculatorTest.class, ParametersTest.class }) // 指定要測試的類 public class TestAll { }
另,在一個套件中也可包含另一個套件類,比如:
再寫一個類TestAll2,其中指定的類是上面的TestAll:
package com.mengdd.junit4; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses(TestAll.class) // 除了指定類,也可以指定套件類 public class TestAll2 { }
總結:
在JUnit4中,如果想要同時運行多個測試類,需要使用兩個注解:
@RunWith(Suite.class)指定使用Suite運行器來運行測試;
@SuiteClasses(ClassName.class)指定運行哪些測試類。測試類可以指定為Suite,這樣JUnit會繼續再去尋找里面的測試類,一直找到能夠執行的Test Case並執行之。
參考資料
聖思園張龍老師視頻教程。
JUnit4 chm格式文檔網盤下載鏈接:
JUnit 4.0:http://pan.baidu.com/share/link?shareid=539345&uk=2701745266