views:

194

answers:

1

So I have this GWT code that handles RPC requests maintain states(ready, waiting, error etc). And I would like to check if the class change its states correctly after each call, set response variables etc.

Now how should I proceed to test that without making actual requests to the server(that could run into errors in the server it self).

I think I could mock the request callback class somehow but it is invisible to the test.

I'm lost, help!

Sample of the code below(I'll post the whole thing later in case anyone wants).

public class RPCHandler
{


  public RPCHandler(String method,String[] argumentsName,
  String[][] argumentsValues)
  {
    this.method = method;
    this.argumentsName = argumentsName;
    this.argumentsValues = argumentsValues;
  }



  /**
   * Method that creates a RPC request using JSON in a POST
   * 
   */
  public void rpcRequest(){
    if(currentState == HandlerState.WAITING_RESPONSE)return;


    currentState = HandlerState.WAITING_RESPONSE;

    // Append watch list stock symbols to query URL.

    url = URL.encode(url);
    url += "action=";
    url += method;

    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

    String requestData = parseToJSON(argumentsName, argumentsValues);

    try{

    Request request = builder.sendRequest(requestData, new RequestCallback()
    {
      public void onError(Request request, Throwable exception)
      {
        setRPCException(new Exception("Error while saving. Action="+method));
        setCurrentState(HandlerState.ON_ERROR);
      }
      //Few other error, response received hander methods after this point.
  }

}
+1  A: 

It looks like you're trying to mock out the actual transport so you should build a mock of the RequestBuilder class. In JMockit, you could write:

public class MockRequestBuilder
{
   public void $init( int method, String url)
   {
     /* check values and/or store for later */
   }

   public Request sendRequest( String data, RequestCallback callback )
   {
     /* check values and/or store for later */
   }
}

You'll need to fill in the details of the what you want the mock to do. Also, you can isolate the callback testing if you moved the callback to a named class instance inside of your outer class:

public class MyGWTClass
{
   protected static class RpcCallback extends RequestCallback
   {
      public void onError(...) { ... }
   }
}

By moving the callback object into a class and using a factory method, you can create tests that only check the callback.

Dan
Used, worked, loved it :D
Diones