How do we use Global variables in Keywords i.e. Groovy scripts

I try to use filepath in my keyword and I don’t what to Hot code it in my groovy script, I thought of creating a a gloval variable and reuse it in Groovy script keyword. Can you please any one help me out on this.

1 Like

I think you could try with:

import internal.GlobalVariable
GlobalVariable G_temp = new GlobalVariable()

Oliver, I tried it but ended-up with the below error:

FAILED because (of) groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.io.File(internal.GlobalVariable), Can you please help me out on this. Below is mu Groovy script

package com.ah.util

import java.nio.*

import com.kms.katalon.core.annotation.Keyword

import internal.GlobalVariable as GlobalVariable

public class Validatefileavailability {

//static void main(String[] args) {

@Keyword

def isDirEmpty(){

GlobalVariable G_FilePath = new GlobalVariable()

// def dir = new File(“D:/Regression/Test data”)

def dir = new File(G_FilePath)

println ((dir.list()))

if ((dir.list() as List).empty)

{

//getAlert(“Input file doesn’t exists”)

println (“Input file doesn’t exists”)

}

else {

println (“Input file exists”)

}

}

}

//}

Ah sorry. To use GlobalVariables, first you need to create it: https://docs.katalon.com/display/KD/Variable+Types#VariableTypes-Globalvariables and then use it in your test case normally. Based on your example, if you would like to use ‘G_FilePath’ variable, then you don’t need to use ‘GlobalVariable G_FilePath = new GlobalVariable()’

@Keyword
def isDirEmpty(){
def dir = new File(G_FilePath)
println ((dir.list()))
if ((dir.list() as List).empty)
{
//getAlert("Input file doesn't exists")
println ("Input file doesn't exists")
}
else {
println ("Input file exists")
}
}
}
//}

I just commented and executed the Keyword ended up with an error that “Variable ‘G_BordereaxFilePath’ is not defined for test case”, Please through some light

Hi @Ramakrishna, have you added the variable: “G_BordereaxFilePath” as Global Variable follow the guideline that Vinh has mentioned above?

I try to check a dir is empty or not with below code and it works fine:

Note: Adding G_FilePath at Global Variable view (you can see added screenshot) . Then use it on script as below:

GlobalVariable.G_FilePath = 'D:\\foldertest'
def dir = new File(GlobalVariable.G_FilePath)
if (dir.isDirectory()) {
if (dir.list().length > 0) {
println ('dir is not empty')
println ((dir.list()))
}else{
println ('dir is empty')
}
}else{
println "this is not a directory"
}

2017-12-19 22_42_43.png