How to check if a global variable already exists

In order to use global variables, Katalon Studio itself has for some time been offering a mechanism that requires the manual configuration of profiles (at least the default profile) of your testing project via the interface.

Sergii Tyshchenko has extended these possibilities by introducing a great method with which global variables can be created and used dynamically, i.e. as required during runtime.

However, to check whether a global variable already exists before it is addressed, a rather complicated and difficult to understand query of the corresponding metaclass property is necessary:

GlobalVariable.metaClass.hasProperty(GlobalVariable, varName)

Therefore, some may find it easier and more convenient to add an exists() method to the GlobalVariable object before using it:

// provide exists() method for global variables:
GroovyShell shell1 = new GroovyShell()
MetaClass mc = shell1.evaluate("internal.GlobalVariable").metaClass
// I made this method a little more specific on February 15th:
mc.'static'.'exists' = { varName -> return GlobalVariable.metaClass.hasProperty(GlobalVariable, varName) != null ? true : false }

For example, this code can be placed in a test listener within a @BeforeTestSuite method.

In this way it is possible to note something like the following in the appropriate place in order to avoid a MissingPropertyException:

String myValue = 'my value'
if (GlobalVariable.exists('g_')) {
    GlobalVariable.g_ = myValue
}
else {
    // create and set variable with Sergii's property constructor (but to be supplemented by a setter method - see my editing below in this post)
    addGlobalVariable('g_', myValue)
}

Or just combine both approaches in another (Keyword) method:

@Keyword
static def setGlobalVariable(String variableName, def variableValue) {
	// I made this method a little more specific on February 15th:
	if (!GlobalVariable.exists(variableName)) {
		addGlobalVariable(variableName, variableValue)
	}
	else {
		GlobalVariable."$variableName" = variableValue
	}
}

Edit:

However, for setting a new value in the above examples to actually work if the variable already exists, the property constructor (addGlobalVariable()) would also need to provide a setter method. Otherwise all dynamically created global variables (i.e. their corresponding properties) would be read-only. But such a setter method was not yet included with Sergii’s above-mentioned approach, as I only understood after my post.

So I thought about the topic again and ended up with a solution, which combines all required methods in a little helper class, which directly extends the capabilities of the GlobalVariable object itself. I will introduce this class in another post soon.

5 Likes