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

DnD*_*DnD 1 java testng

我使用testNGSelenium webdriver2.0.

在我的testNG.xml

<suite data-provider-thread-count="2" name="selenium FrontEnd Test" parallel="false" skipfailedinvocationCounts="false" thread-count="2">
  <parameter name="config_file" value="src/test/resources/config.properties/"/>
  <test annotations="JDK" junit="false" name="CarInsurance Sanity Test" skipfailedinvocationCounts="false" verbose="2">
    <parameter name="config-file" value="src/test/resources/config.properties/"/>
    <groups>
      <run>
        <include name="abstract"/>
        <include name="Sanity"/>
      </run>
    </groups>
    <classes>
    </classes>
  </test> 
</suite>
Run Code Online (Sandbox Code Playgroud)

在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");

}
Run Code Online (Sandbox Code Playgroud)

得到错误

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

如何使用@Parameters资源文件?

art*_*nil 9

看起来您的config-file参数未在该<suite>级别定义.有几种方法可以解决这个问题:1.确保<parameter>元素在<suite>tag中定义但在any之外<test>:

 <suite name="Suite1" >
   <parameter name="config-file" value="src/test/resources/config.properties/" />
   <test name="Test1" >
      <!-- not here -->
   </test>
 </suite>
Run Code Online (Sandbox Code Playgroud)

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

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

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

选项1:

<suite>
  <parameter name="config-file" value="src/test/resources/config.properties/"/>
  <test >
    <groups>
      <run>
        <include name="abstract"/>
        <include name="Sanity"/>
      </run>
    </groups>
    <classes>
      <!--put classes here -->
    </classes>
  </test> 
</suite>
Run Code Online (Sandbox Code Playgroud)

选项2:

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

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