I can wrap a Java function like this:
* def myJavaMethod =
"""
function() {
var Utils = Java.type('Utils');
// use Number type in constructor
var obj = new Utils(...);
return obj.myJavaMethod();
}
"""
But why would I? I can use Java functions straight in the test scenarios, like this:
Scenario: Test exec and error value
* def Utils = Java.type('Utils');
* def ret = Utils.exec('echo "From Java" > /home/richard//karate-test/karate-0.9.6/out.txt');
* match read('out.txt') == "From Java\n";
* match Utils.exec('exit 123') == 123
Note: exec
is a static method that uses a shell to execute the command given.
At least I tested this for static methods and that works fine without the JavaScript detour. It seems that the JavaScript wrapper only adds an extra layer of complication. Besides that, with the 'call' syntax I can only pass one parameter (that admittedly can be an entire object or array). But, I can pass parameters straight to a Java function (using normal syntax) and even use the result in a match. (I assume parameters and results are implicitly converted to a JavaScript value, that could be a JSON object or array).
So far, I miss to see the advantage of explicitly wrapping Java code inside JavaScript wrappers. I assume the problem is me, that is: I am missing some important point here?
The only advantage is to reduce typing and when you have a lot of code re-use. For example, instead of:
You define it once:
And then call it wherever, and it is super-concise: