views:

65

answers:

2

Hi,

I've built a thin GWT Wrapper around an existing JavaScript API. The JavaScript API is independently tested, so all I want to do is test that the GWT Wrapper calls the correct JavaScript functions with the correct arguments. Any ideas on how to go about doing this?

Currently, the GWT API has a bunch of public methods which after a bit of processing call private native methods which make the JavaScript API calls.

Any guidance appreciated, thanks.

+1  A: 

The best way to determine if a function has fired is to make a function write to a closure and then test for the value of the closure. Since a closure is a variable you can define it as a function argument, but that definition would have to occur upon a parent function.

+2  A: 

In the java world, what you asked for is usually done using delegation and interfaces.

I would make a (java) interface that corresponds one to one with the API that the js library, and then create a simple implementation of that interface.

Your wrapper code then wraps the interface instead. During test time, you replace the implementation of that interface with your own, where each method just asserts whether it is called or not.

E.g.

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);}
}
Chii
Thanks - very helpful examples
Supertux