How to use testNG @Parameters in @BeforeSuite to read resource file

后端 未结 2 1940
广开言路
广开言路 2021-01-01 08:06

I am using testNG with Selenium webdriver2.0.

In my testNG.xml I have



        
相关标签:
2条回答
  • 2021-01-01 08:31

    You want to use @Parameter in @BeforeSuite. Suite level parameters are parsed once the suite begins execution and I believe TestNG invokes @BeforeSuite even before the suite is processed:

    Here is a workaround: add ITestContext in method parameters to inject

    @BeforeSuite(groups = { "abstract" } )
    @Parameters({ "configFile" })
    public void initFramework(ITestContext context, String configFile) throws Exception {
    
    0 讨论(0)
  • 2021-01-01 08:32

    Looks like your config-file parameter is not defined at the <suite> level. There are several ways to solve this: 1. Make sure the <parameter> element is defined within <suite> tag but outside of any <test>:

     <suite name="Suite1" >
       <parameter name="config-file" value="src/test/resources/config.properties/" />
       <test name="Test1" >
          <!-- not here -->
       </test>
     </suite>
    

    2. If you want to have the default value for the parameter in the Java code despite the fact it is specified in testng.xml or not, you can add @Optional annotation to the method parameter:

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

    EDIT (based on posted testng.xml):

    Option 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>
    

    Option 2:

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

    In any case, I would recommend not having two parameters with almost identical names, identical values, and different scope.

    0 讨论(0)
提交回复
热议问题