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 Integer //TEST def test_validate_name(){ def responseContent = testRunner.testCase.testSuite.project.getPropertyValue( "response" ) def slurperresponse = new JsonSlurper().parseText(responseContent) float expected_value = 200 float[] a = slurperresponse.values.DATA.FILE.[0].value float actual_value = a.collect { "$it" }.join( '' ) as float assert actual_value <= expected_value }
It works if i keep this line inside the medthod:
float expected_value = 200
If i put comment on this line and use the variable from outside the method with this line:
def expected_value = testRunner.testCase.testSuite.project.getPropertyValue("value") as Integer
it throws error: java.lang.NullPointerException: Cannot invoke method test_validate_name() on null object
I tried with this set.context('{Project#value}') it doesn't work.
Do you have any suggestions ?
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.