2012-09-29 118 views
2


有人在这里使用GWT SyncProxy的经验吗?
我尝试测试异步rpc,但onFailure和onSuccess下的代码未经测试。不幸的是,没有错误日志,但也许有人可以帮助我。这个例子是从这个页面:http://code.google.com/p/gwt-syncproxy/测试异步rpc

编辑:
我想测试结果失败。所以我加了'assertNull(result);'。奇怪的是,控制台首先给出'异步好',然后'异步坏'。所以该功能运行两次?!而Junit的结果是绿色的。

public class Greeet extends TestCase { 
@Test 
public void testGreetingServiceAsync() throws Exception { 
     GreetingServiceAsync rpcServiceAsync = (GreetingServiceAsync) SyncProxy.newProxyInstance(
     GreetingServiceAsync.class, 
     "http://127.0.0.1:8888/greettest/", "greet"); 

     rpcServiceAsync.greetServer("SyncProxy", new AsyncCallback<String>() { 
     public void onFailure(Throwable caught) { 
      System.out.println("Async bad "); 
     } 
     public void onSuccess(String result) { 
      System.out.println("Async good "); 
      assertNull(result); 
     } 
     }); 

     Thread.sleep(100); // configure a sleep time similar to the time spend by the request 
} 
} 

回答

1

为了使用GWT-syncproxy测试:

  1. 你必须启动GWT服务器: 'MVN GWT:运行' 如果你正在使用maven或“项目 - >运行为 - >网络应用程序“,如果你在日食。
  2. 您必须设置服务的URL,通常为'http://127.0.0.1:8888/your_module'。请注意,在您的示例中,您正在使用应用程序html的url。
  3. 如果你测试异步,你必须等到通话结束,所以在你的情况下,你需要一个Thread.sleep(某个时间)在你的方法结束。
  4. 如果测试同步,则不需要睡眠。

这两个例子测试用例:

同步测试

public void testGreetingServiceSync() throws Exception { 
    GreetingService rpcService = (GreetingService)SyncProxy.newProxyInstance(
    GreetingService.class, 
    "http://127.0.0.1:8888/rpcsample/", "greet"); 
    String s = rpcService.greetServer("SyncProxy"); 
    System.out.println("Sync good " + s); 
} 

异步测试

boolean finishOk = false; 
public void testGreetingServiceAsync() throws Exception { 
    GreetingServiceAsync rpcServiceAsync = (GreetingServiceAsync) SyncProxy.newProxyInstance(
    GreetingServiceAsync.class, 
    "http://127.0.0.1:8888/rpcsample/", "greet"); 

    finishOk = false; 
    rpcServiceAsync.greetServer("SyncProxy", new AsyncCallback<String>() { 
    public void onFailure(Throwable caught) { 
     caught.printStackTrace(); 
    } 

    public void onSuccess(String result) { 
     assertNull(result); 
     finishOk = true; 
    } 
    }); 

    Thread.sleep(100); 
    assertTrue("A timeout or error happenned in onSuccess", finishOk); 
} 
+0

谢谢。但是我已经更新了我的问题,因为我还有一个奇怪的问题。 – user1701135

+0

是否有任何理由做异步测试?如果你是单元测试你的服务,它应该足以使用异步方法。 –

+0

异步代理实现不会在成功调用期间抛出失败,因此您必须维护一个标志以查看测试是否失败。我更新了我的例子。 –