[英]How to run all JUnit tests of a given package?
我在eclipse中使用JUnit 4。 我的包中有一些測試類,想要運行它們。 怎么樣?
右鍵單擊包瀏覽器中的包,然后選擇“運行方式”和“單元測試”。
在eclipse中,如果右鍵單擊該文件夾並選擇Run As JUnit Test,則只運行該文件夾中的測試(即不會運行嵌套子文件夾中的測試)。 為了在包含嵌套目錄中的測試的目錄中運行所有測試,您需要使用googlecode.junittool框之類的東西。
使用這個我創建了類似下面的內容
package com.mycompany.myproject.mymodule;
import org.junit.runner.RunWith;
import com.googlecode.junittoolbox.SuiteClasses;
import com.googlecode.junittoolbox.WildcardPatternSuite;
@RunWith(WildcardPatternSuite.class)
@SuiteClasses({ "**/*Test.class" })
public class RunAllMyModuleTests {
}
我在我的mavin構建中添加了所需的依賴項(jar文件)(除了junit依賴項):
<dependency>
<groupId>com.googlecode.junit-toolbox</groupId>
<artifactId>junit-toolbox</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
</dependency>
右鍵單擊此類並選擇Run As JUnit test將運行指定目錄中的所有測試,包括嵌套子文件夾中的所有測試。
我曾經聲明一個AllTests
類,所以我也可以從命令行運行所有測試:
public final class AllTests
{
/**
* Returns a <code>TestSuite</code> instance that contains all the declared
* <code>TestCase</code> to run.
*
* @return a <code>TestSuite</code> instance.
*/
public static Test suite()
{
final TestSuite suite = new TestSuite("All Tests");
suite.addTest(Test1.suite());
suite.addTest(Test2.suite());
suite.addTest(Test3.suite());
return suite;
}
/**
* Launches all the tests with a text mode test runner.
*
* @param args ignored
*/
public static final void main(String[] args)
{
junit.textui.TestRunner.run(AllTests.suite());
}
} // AllTests
每個測試類定義的位置
/**
* Returns a <code>TestSuite</code> instance that contains all
* the declared <code>TestCase</code> to run.
*
* @return a <code>TestSuite</code> instance.
*/
public static final Test suite()
{
return new TestSuite(Test1.class); // change the class accordingly
}
使用JUnit 4我喜歡使用帶注釋的AllTests
類:
@RunWith(Suite.class)
@Suite.SuiteClasses({
// package1
Class1Test.class,
Class2test.class,
...
// package2
Class3Test.class,
Class4test.class,
...
})
public class AllTests {
// Junit tests
}
並且,為了確保我們不會忘記添加TestCase,我有一個覆蓋測試(還檢查是否正在測試每個公共方法)。
在包瀏覽器中,您可以使用包的上下文菜單,並選擇run as junit test
。
使用JUnit5,您可以輕松創建一個“套件”類,它將在包中運行所有測試(甚至是子包,它以遞歸方式工作):
@RunWith(JUnitPlatform.class)
@SelectPackages("my.test.package")
public class MySuite {
}
完成后,您可以使用“Run as Test”運行此套件。
右鍵單擊包,然后從“運行方式”子菜單中選擇“運行為測試”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.