![](/img/trans.png)
[英]Why does a JUnit suite class not execute its own Test, Before, and After annotations?
[英]Java - JUnit - Execute @Test Annotations in Child Class
父 Class:
@BeforeTest
public void prepareTest()
@Test
public void runTest()
@AfterMethod
public void tearDown()
@AfterTest
public void endReport()
測試用例類目錄:
測試文件夾
--> 測試用例1
--> 測試用例2
--> 測試用例3
在每個測試用例 class 文件中,我有不同數量的方法,顯然取決於測試用例。 但是為了執行這些方法,我必須在每個測試用例中創建一個名為executeTest的方法。 在這個方法中,我按照我需要的順序調用 class 文件中的所有方法。
public boolean executeTest()
{
myMethod1()
myMethod2()
myMethod3()
myMethod4()
return true;
}
然后,在我的父 class 的 runTest 方法中,我有一個方法調用來調用子 class 中的executeTest方法。
這一切都很好,但我想要做的是遠離子類中的方法,而是將@Test注釋分配給每個方法,並優先考慮執行順序。
像這樣的東西:
@Test(priority = 1)
myMethod1()
@Test(priority = 2)
myMethod2()
@Test(priority = 3)
myMethod3()
@Test(priority = 4)
myMethod4()
這有可能實現嗎? 有沒有更好的方法來做到這一點?
編輯:
這是我用來在子類中調用方法 executeTest 的 function:
public boolean executeMethod(String className)
{
//https://stackoverflow.com/questions/18778819/dynamically-calling-a-class-method-in-java
//https://stackoverflow.com/questions/5266532/can-i-get-all-methods-of-a-class
//String methodNames[] = new String[]{"executeTest"};
String mName = "";
try {
Class classRef = Class.forName(className);
Object instance = classRef.newInstance();
Method[] methodNames = classRef.getDeclaredMethods();
for (Method methodName : methodNames)
{
mName = methodName.getName();
try
{
if(mName.equalsIgnoreCase("executeTest"))
{
Method method = classRef.getDeclaredMethod(mName);
method.invoke(instance);
}
}
catch (NoSuchMethodException | SecurityException | IllegalArgumentException ex)
{
ex.printStackTrace();
}
catch(InvocationTargetException e)
{
if(e.getCause().toString().toLowerCase().contains("TestException".toLowerCase()))
{
throw new TestException();
}
}
}
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex)
{
ex.printStackTrace();
}
return true;
}
在我的父 class 文件中,在 runTest 方法中,我這樣稱呼它:
executeMethod(projectName + "." + TestCase);
您可以使用@Order
注解在 JUnit5 中設置優先級。
@TestMethodOrder(OrderAnnotation.class)
public class JUnit5TestOrder {
@Test
@Order(1)
public void Testcase_3() {
System.out.println("Testcase_3 executes");
}
@Test
@Order(2)
public void Testcase_1() {
System.out.println("Testcase_1 executes");
}
@Test
@Order(3)
public void Testcase_2() {
System.out.println("Testcase_2 executes ");
}
}
在JUnit4
中,您可以使用@FixedMethodOrder
對測試用例進行排序。 有關更多詳細信息,請查看JUnit 測試執行順序。
@FixMethodOrder(MethodSorters.DEFAULT)
public class JUnit4TestOrder {
@Test
public void Testcase_3() {
System.out.println("Testcase_3 executes");
}
@Test
public void Testcase_1() {
System.out.println("Testcase_1 executes");
}
@Test
public void Testcase_2() {
System.out.println("Testcase_2 executes ");
} }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.