简体   繁体   English

在空手道中,将 Java function 包装在 JavaScript ZC1C5145268C40C1C1C5145268C40A 中的优势是什么?

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

I can wrap a Java function like this:我可以像这样包装 Java function :

* 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:我可以在测试场景中直接使用 Java 函数,如下所示:

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.注意: exec是一个 static 方法,它使用 shell 来执行给定的命令。

At least I tested this for static methods and that works fine without the JavaScript detour.至少我对static方法进行了测试,并且在没有 JavaScript 绕道的情况下工作正常。 It seems that the JavaScript wrapper only adds an extra layer of complication.似乎 JavaScript 包装器只会增加额外的复杂性。 Besides that, with the 'call' syntax I can only pass one parameter (that admittedly can be an entire object or array).除此之外,使用“调用”语法,我只能传递一个参数(不可否认,它可以是整个 object 或数组)。 But, I can pass parameters straight to a Java function (using normal syntax) and even use the result in a match.但是,我可以将参数直接传递给 Java function (使用正常语法),甚至在匹配中使用结果。 (I assume parameters and results are implicitly converted to a JavaScript value, that could be a JSON object or array). (我假设参数和结果被隐式转换为 JavaScript 值,这可能是 JSON object 或数组)。

So far, I miss to see the advantage of explicitly wrapping Java code inside JavaScript wrappers.到目前为止,我还没有看到在 JavaScript 包装器中显式包装 Java 代码的优势。 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())' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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