我围绕现有的 JavaScript API 构建了一个瘦 GWT 包装器。 JavaScript API 是独立测试的,所以我只想测试 GWT Wrapper 是否使用正确的参数调用正确的 JavaScript 函数。关于如何进行此操作的任何想法?
目前,GWT API 有一堆公共(public)方法,这些方法在经过一些处理后调用私有(private) native 方法,从而调用 JavaScript API。
任何指导表示赞赏,谢谢。
最佳答案
在 Java 世界中,您所要求的通常是使用委托(delegate)和接口(interface)来完成的。
我会创建一个与 js 库的 API 一对一对应的 (java) 接口(interface),然后创建该接口(interface)的简单实现。
然后您的包装器代码将接口(interface)包装起来。在测试期间,您用自己的接口(interface)替换该接口(interface)的实现,其中每个方法只是断言它是否被调用。
例如
custom.lib.js has these exported methods/objects:
var exports = {
method1: function(i) {...},
method2: function() {...},
...etc
}
your custom interface:
public interface CustomLib {
String method1(int i);
void method2();
//...etc etc
}
your simple impl of CustomLib:
public class CustomLibImpl implements CustomLib {
public CustomLibImpl() {
initJS();
}
private native void initJS()/*-{
//...init the custom lib here, e.g.
$wnd.YOUR_NAME_SPACE.customlib = CUSTOMLIB.newObject("blah", 123, "fake");
}-*/;
public native String method1(int i)/*-{
return $wnd.YOUR_NAME_SPACE.customlib.method1(i);
}-*/;
void method2()/*-{
$wnd.YOUR_NAME_SPACE.customlib.method2();
}-*/;
//...etc etc
}
then in your Wrapper class:
public class Wrapper {
private CustomLib customLib;
public Wrapper(CustomLib customLib ) {
this.customLib = customLib;
}
public String yourAPIMethod1(int i) {
return customLib.method1(i);
}
///etc for method2()
}
your test:
public class YourCustomWrapperTest {
Wrapper wrapper;
public void setup() {
wrapper = new Wrapper(new CustomLib() {
//a new impl that just do asserts, no jsni, no logic.
public String method1(int i) {assertCalledWith(i);}
public void method2() {assertNeverCalledTwice();}
//etc with other methods
});
}
public void testSomething() { wrapper.yourAPIMethod1(1);}
}
关于javascript - 如何测试在 GWT 中使用正确的参数调用了一些 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1454160/