简体   繁体   中英

In Karate, what is the advantage of wrapping a Java function in a JavaScript function?

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:

* def foo = java.util.UUID.randomUUID() + ''

You define it once:

* def uuid = function(){ return java.util.UUID.randomUUID() + '' }

And then call it wherever, and it is super-concise:

* def json = { foo: '#(uuid())' }

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