简体   繁体   中英

having trouble passing args from java to groovy script

I am trying to write a cucumber test (using cucumber-jvm) to run a groovy script on a sample file and verify that the data is properly stored in a db. (I did not write the groovy script, which runs just fine from the command line). I can't seem to get the args into the groovy script properly. Can anyone tell me how to get this to work?

The groovy script has the following code:

/** Check command line options.  */
def cli = new CliBuilder(usage: 'groovy scriptname.groovy [-h] -f file')
cli.h(longOpt: 'help', 'Usage information', required: false)
cli.f(longOpt: 'file', 'File with information', args: 1)

OptionAccessor opt = cli.parse(args)
if(!opt) {
  return
}
else if(opt.h || !opt.f) {
  cli.usage()
  return
}
/** Process file.  */
def file = new File(opt.f)

My java code contains the following:

final GroovyShell shell = new GroovyShell();
final Binding binding = new Binding();
final String[] args = {"-f", fileFn};
binding.setVariable("args", args);
final File file = new File(scriptFn);
final Script script = shell.parse(file);
script.run();

The groovy script works just fine when run from the command line. When I run it from the java/cucumber step definition, I get the error:

groovy.lang.MissingPropertyException: No such property: args for class: FWLoader
at FWLoader.run(FWLoader.groovy:171)

The line in the groovy script that is failing is

OptionAccessor opt = cli.parse(args)

Any suggestions? I am new to groovy and fairly new to java (many years programming in C/C++ though).

it's maybe a typo, but you are missing a script.setBinding(binding) :

final Script script = shell.parse(file);
script.setBinding(binding); // <-- here
script.run();

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