如何在@BeforeSuite中使用testNG @Parameters来读取资源文件

我正在使用带有Selenium webdriver2.0 testNG

在我的testNG.xml我有

               

在java文件中

 @BeforeSuite(groups = { "abstract" } ) @Parameters(value = { "config-file" }) public void initFramework(String configfile) throws Exception { Reporter.log("Invoked init Method \n",true); Properties p = new Properties(); FileInputStream conf = new FileInputStream(configfile); p.load(conf); siteurl = p.getProperty("BASEURL"); browser = p.getProperty("BROWSER"); browserloc = p.getProperty("BROWSERLOC"); } 

得到错误

AILED CONFIGURATION:@BeforeSuite initFramework org.testng.TestNGException:@Configuration在方法initFramework上需要参数’config-file’,但尚未标记为@Optional或在

如何将@Parameters用于资源文件?

看起来您的config-file参数未在级别定义。 有几种方法可以解决这个问题:1。确保元素在标记内定义,但在任何

        

2.如果您希望在Java代码中具有参数的默认值,尽管它是否在testng.xml指定,您可以将@Optional注释添加到method参数:

 @BeforeSuite @Parameters( {"config-file"} ) public void initFramework(@Optional("src/test/resources/config.properties/") String configfile) { //method implementation here } 

编辑 (基于发布的testng.xml):

选项1:

               

选项2:

 @BeforeTest @Parameters( {"config-file"} ) public void initFramework(@Optional("src/test/resources/config.properties/") String configfile) { //method implementation here } 

无论如何,我建议不要让两个参数具有几乎相同的名称,相同的值和不同的范围。

你想在@Parameter中使用@BeforeSuite 。 套件开始执行后会解析套件级参数,我相信TestNG甚至在处理套件之前就会调用@BeforeSuite

这是一个解决方法:在方法参数中添加ITestContext以进行注入

 @BeforeSuite(groups = { "abstract" } ) @Parameters({ "configFile" }) public void initFramework(ITestContext context, String configFile) throws Exception {