【发布时间】:2021-04-30 23:18:42
【问题描述】:
父类:
@BeforeTest
public void prepareTest()
@Test
public void runTest()
@AfterMethod
public void tearDown()
@AfterTest
public void endReport()
测试用例类目录:
测试文件夹
--> 测试用例1
--> 测试用例2
--> 测试用例3
在每个测试用例类文件中,我有不同数量的方法,显然取决于测试用例。但是为了执行这些方法,我必须在每个测试用例中创建一个名为 executeTest 的方法。在这个方法中,我按照需要的顺序调用该类文件中的所有方法。
public boolean executeTest()
{
myMethod1()
myMethod2()
myMethod3()
myMethod4()
return true;
}
然后,在我的父类中的 runTest 方法中,我有一个方法调用来调用子类中的 executeTest 方法。
这一切都很好,但我想要做的是摆脱子类中的方法,而是将@Test注解分配给每个方法,并优先考虑执行顺序。
类似这样的:
@Test(priority = 1)
myMethod1()
@Test(priority = 2)
myMethod2()
@Test(priority = 3)
myMethod3()
@Test(priority = 4)
myMethod4()
这可以实现吗?有没有更好的方法呢?
编辑:
这是我用来在子类中调用方法 executeTest 的函数:
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;
}
在我的父类文件中,在 runTest 方法中,我这样称呼它:
executeMethod(projectName + "." + TestCase);
【问题讨论】: