cancel
Showing results for 
Search instead for 
Did you mean: 

How to access a variable outside a method in groovy ?

SOLVED
Community Hero

Re: How to access a variable outside a method in groovy ?

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.

 



Regards,
Rao.

View solution in original post

Highlighted
Community Hero

Re: How to access a variable outside a method in groovy ?

Further improvement can be to make the method static to simplify the usage while calling the library methods if it does not require any instance specific variables and most of the libary cases here can be static unless some specifics need to create instance of the class.

From

def showValue(log, testRunner)



To

static def showValue(log, testRunner)


And usage in the Groovy script test would not require to create instance of the class. Instead method can be directly called.

Utility.showValue(log, testRunner)

 



Regards,
Rao.
New Here?
Join us and watch the welcome video:
Top Kudoed Authors