有没有办法在 AbstractBase 类中将用户定义的参数从方法注入到方法之前的方法



在方法中,我从 excel 获取我的测试用例名称,该名称使用数据提供程序传递给方法。我想在@beforemethod中传递该测试用例名称(在不同的类中定义,即AbstractBaseclass,方法类正在扩展此AbstractBaseClass(,我在其中启动了范围报告。我想通过测试用例名称开始我的报告。

有没有办法将测试用例名称作为参数从方法传递到@beforemethod

这是你如何做到的。TestNG 允许您将Object[]数组注入到@BeforeMethod注释方法中。当 TestNG 看到对象数组时,它会本机注入即将传递给数据驱动@Test方法的参数。请参阅此 TestNG wiki 页面,以了解有关 TestNG 作为原生注入的一部分所允许的所有内容的更多信息。

基类的外观如下:

import org.testng.annotations.BeforeMethod;
public class AbstractBaseClass {
@BeforeMethod
public void beforeMethod(Object[] parameters) {
//Here we are assuming that the testname will always be the first parameter
//in the 1D array that gets sent for every iteration of @Test method
if (parameters != null && parameters.length >= 1) {
String testname = parameters[0].toString();
System.out.println("Test name obtained in beforeMethod() " + testname);
}
}
}

这是您的测试类的外观

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestClass extends AbstractBaseClass {
@Test(dataProvider = "getData")
public void testMethod(String testname, int count) {
Assert.assertNotNull(testname);
Assert.assertTrue(count > 0);
}
@DataProvider
public Object[][] getData() {
return new Object[][]{
{"LoginTestCase", 100},
{"ComposeMailTestcase", 200}
};
}
}

这样,您可以在基类本身中获取测试名称,即使它是通过数据提供程序输入的。

与往常一样,请确保您使用的是TestNG 6.11(截至今天2017年7月20日是TestNG的最新发布版本(

最新更新