我正在使用 TestNG 进行 Selenium 测试。 有一个名为“Create Firm”的测试,需要在我的笔记本电脑上运行多次。
所以我为此编写了一个名为“CreateFirm”的类,各个公司的数据驻留在 Excel 电子表格中。
在不同的时间,我需要创建不同的公司集,我使用 Excel 电子表格中的一列来控制这些公司,该列保存我的计算机名称。
我使用 @Factory 创建“CreateFirm”类,该类有一个 @Test 方法来创建公司。
在 Excel 电子表格中,如果我以相同的顺序将 Firm1、Firm2、Firm3、Firm4 分配给我的笔记本电脑,@Factory 将按随机顺序创建它们,例如 Firm4、Firm3、Firm1、Firm2
我的问题是如何让@Factory按照我想要的顺序创建测试实例?
我的@Factory方法是
@Factory
public Object[] runCreateFirm()
{
//This is where I get the list of test cases assigned to my laptop
this.test_id_list=get_test_ids_for_test_run("Create Firm (class approach).xls", "Global");
Object[] result = new Object[this.test_id_list.size()];
int index=0 ;
for (String firm_id: this.test_id_list)
{
//This is where I get all the test data from the Excel spreadsheet
HashMap<String,String> test_data_row=this.get_row_from_excel("Create Firm (class approach).xls", "Global", "test_case_id", firm_id);
System.out.println("Inside Firm Factory ,index="+index +", test case id="+ test_data_row.get("test_case_id"));
//CreateFirm is the class which will use the data and do all the UI actions to create a Firm
result[index]=new CreateFirm(test_data_row);
index++;
}
return result;
}
XML 是
<?xml version="1.0" encoding="UTF-8"?>
<suite name="CreateFirm Suite">
<test name="Create Firm Test" order-by-instances="false">
<classes>
<class name="regressionTests.factory.CreateFirmFactory"/>
</classes>
</test>
</suite>
最佳答案
设法根据我的要求编写拦截器方法。 首先,我在类(class)中引入了一个新领域,称为“优先级”。我无法使用@Priority,因为我的测试类只有一种测试方法,在这种情况下,我的所有实例化都将具有相同的优先级。 因此,我引入了一个称为优先级的新字段,它将具有实例化类的顺序。我在拦截器方法中使用该字段来设置实例化的顺序
public List<IMethodInstance> intercept(List<IMethodInstance> methods,ITestContext context)
{
List<IMethodInstance> result = new ArrayList<IMethodInstance>();
int array_index=0;
for (IMethodInstance m : methods)
{
result.add(m);
}
//Now iterate through each of these test methods
for (IMethodInstance m : methods)
{
try {
//Get the FIELD object from - Methodobj->method->class->field
Field f = m.getMethod().getRealClass().getField("priority");
//Get the object instance of the method object
array_index=f.getInt(m.getInstance());
}
catch (Exception e) {
e.printStackTrace();
}
result.set(array_index-1, m);
}
return result;
}
关于java - 如何让 TestNG-@Factory 以特定顺序实例化测试类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783989/