javascript - 如何测试在 GWT 中使用正确的参数调用了一些 JavaScript?

标签 javascript testing gwt

我围绕现有的 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/

相关文章:

unit-testing - 单元测试 SignalR 集线器

javascript - 如何监听页面加载时触发的事件

java - 如何在 GWT 中实现 JQueryUI slider

java - 按 T​​ab 键时,重点不要转到 GXT EditorGrid 中的下一个字段

javascript - 如何使用 Ajax 提交成功后重新加载特定表单?

javascript - 想要在向下滚动到顶部时更改悬停时的导航链接颜色 --jquery

javascript - rxjs5 - 通过每个对象包含的可观察对象过滤对象数组

javascript - 如何将 PHP 变量的 while 循环作为 JSON 组件传递到 JS 脚本中?

java - 如何在方法中测试业务逻辑?

java - 如何使用生成器修改 CssResource 的 css 文件?