简体   繁体   中英

How to define constants which can be used in multiple script files in Groovy?

I'm writing tests in JMeter environment. Leveraging on groovy and writing re-usable code resulted that we will have multiple script files and a single one where the constants are defined. And here is my question, how is possible to access to constants defined in a file from the script files?

Why it is important for me? There are decision points in the logic of the test cases, and there is some data placed in Jmeter.props global variable where the key is string. I'd like to store these keys in a constant class to avoid typos in the future.

I'd like to achieve something similar:

Groovy file 1

class Constants {
    public final static String PREFIX = 'prefix'
}

Groovy file 2

void methodName() {

    printlin("===> " + Constants.PREFIX)
}

methodName()
===> prefix

First try was something similar:

Groovy file 1

class Constants {
    public final static String PREFIX = "prefix"
}

Groovy file 2

void methodName() {

    printlin("===> " + Constants.PREFIX)
}

methodName()

which resulted in an error message where the compiler was looking for Constants property of methodName.ScriptWhatever class This case the files were in the same package.

The second try was dealing with @Fields, but I couldn't figure out how is possible to distribute the values of the constants in the way you have define them only a single place.

The funny was that, I included one of these constants like the following and it worked...

void methodName() {

    printLn("===> " + Inspector.CLASS_CLASS_IDX)
}

methodName()

If I remember correctly, in java you can solve this problem like this:

public class Constants {
    public static final String PREFIX = "prefix";
}

public class AnotherClass {
    public void doIt() { System.out.println(Constants.PREFIX); }
}

And the result is "prefix" (Sorry, my java knowledge is pretty rusty still)

All your constant classes (scripts) must be visible, ie be present in class-path of execution environments for all other scripts. Otherwise you would be getting NoSuch*Exception s.

I'm not an expert on groovy class-free wild scripting, but off the hip your can try packaging your constant class/-es into a .jar file and use @Grab annotation in other scripts to reference the former.

按照@ dagett33的建议,我将生成的jar添加到jmeter的lib目录中,如我先前的文章中所述 ,它可以正常工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM