【问题标题】:How do I test some JavaScript was called with the correct arguments in GWT?如何测试在 GWT 中使用正确参数调用的某些 JavaScript?
【发布时间】:2009-09-21 11:56:05
【问题描述】:
我围绕现有的 JavaScript API 构建了一个精简的 GWT 包装器。 JavaScript API 是独立测试的,所以我要做的就是测试 GWT Wrapper 是否使用正确的参数调用正确的 JavaScript 函数。关于如何进行此操作的任何想法?
目前,GWT API 有一堆公共方法,经过一些处理后调用私有的本地方法,这些方法会调用 JavaScript API。
感谢任何指导,谢谢。
【问题讨论】:
标签:
javascript
testing
gwt
【解决方案1】:
在 Java 世界中,您所要求的通常是使用委托和接口来完成的。
我会创建一个与 js 库的 API 一一对应的(java)接口,然后创建该接口的简单实现。
然后,您的包装器代码会包装接口。在测试期间,您用您自己的接口替换该接口的实现,其中每个方法只是断言它是否被调用。
例如
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);}
}
【解决方案2】:
确定函数是否已触发的最佳方法是让函数写入闭包,然后测试闭包的值。由于闭包是一个变量,您可以将其定义为函数参数,但该定义必须发生在父函数上。