Forum Discussion

_ivanovich_'s avatar
_ivanovich_
Frequent Contributor
5 years ago
Solved

How to access a variable outside a method in groovy ?

Hi,  i have a variable at project leve like: ${#Project#value}  i have a groovy step with this: //VAR //def expected_value = testRunner.testCase.testSuite.project.getPropertyValue("value") as Inte...
  • nmrao's avatar
    5 years ago

    Here is an example how to define the class defined in the script library, and usually making mistakes.

     

    /**
    * Class in the script library
    * which can be called or re-used from any groovy test step
    *
    **/
    class Utility {
        def showValue() {
    	log.info testRunner.testCase.testSuite.project.getPropertyValue( "USER_PROPERTY" )
        }
    }

    When user tried to use above showValue in groovy script:

     

    def util = new Utility()
    util.showValue()

    Then user would get below error:

       groovy.lang.MissingPropertyException: No such property: log for class: Utility

    The same is applicable for testRunner as well.

     

    That is because, only groovy script test step knows variables log, testRunner ; however, Class or its methods don't know them.

    Now the question is how access them in script library class methods?

    The answer is simple, pass those variables from groovy script test step as arguments to the method i.e., change the signature of showValue method to have log and testRunner as parameters.

     

    The changes are

     

    /**
    * Class in the script library
    * which can be called or re-used from any groovy test step
    *
    **/
    class Utility {
        def showValue(log, testRunner) {
    		log.info testRunner.testCase.testSuite.project.getPropertyValue( "USER_PROPERTY" )
        }
    }

    And statements in groovy script would be:

     

    def util = new Utility()
    util.showValue(log, testRunner)

    The above changes just works without error.

     _ivanovich_ see if the above example is helpful to resolve the issue.