追求代码质量: 对 Ajax 应用程序进行单元测试

发表于:2007-8-09 16:36

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Andrew Glover    来源:IBM

分享:

功能性和集成测试

        图 2 所示的交互测试可用于多个不同场景,但是其中两种场景最为常见。从功能性观点考虑,您或许希望编写一个测试:填入表单值,单击 Submit 按钮,然后验证表单是否显示定义。另外一个选择是集成测试,使您能够验证客户端代码的异步功能。GWT 的 GWTTestCase 正是被设计用来执行此类测试。

        需要牢记的是:在 GWTTestCase 测试用例环境下不可以进行用户界面测试。在设计和构建 GWT 应用程序时,您必须清楚不要依赖用户界面 测试代码。这种思路需要把交互代码从业务逻辑中分离出来,正如您已经了解的,这是最佳的入门实践!

        举例而言,重新查看图 1 和图 2 所示的 Ajax 应用程序。该应用程序由四个逻辑部分构成:TextBox 用于输入目标单词,Button 用于执行单击,还有两个 Label(一个用于 TextBox,另一个显示定义)。实际 GWT 模块的初始方法如清单 1 所示,但是您该如何测试这段代码呢?


清单 1. 一个有效的 GWT 应用程序,但是如何测试它?
               
public class DefaultModule implements EntryPoint {

 public void onModuleLoad() {
   Button button = new Button("Submit");
   TextBox box = new TextBox();
   Label output = new Label();
   Label label = new Label("Word: ");

   HorizontalPanel inputPanel = new HorizontalPanel();
   inputPanel.setStyleName("input-panel");
   inputPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
   inputPanel.add(label);
   inputPanel.add(box);

   button.addClickListener(new ClickListener() {
    public void onclick(Widget sender) {
      String word = box.getText();
      WordServiceAsync instance = WordService.Util.getInstance();
       try {
         instance.getDefinition(word, new AsyncCallback() {
          
           public void onFailure(Throwable error) {
             Window.alert("Error occurred:" + error.toString());
           }

           public void onSuccess(Object retValue) {
             output.setText(retValue.toString());
           }
    });
        }catch(Exception e) {
          e.printStackTrace();
  }
 }
   });

   inputPanel.add(button);
   inputPanel.setCellVerticalAlignment(button,
     HasVerticalAlignment.ALIGN_BOTTOM);

   RootPanel.get("slot1").add(inputPanel);
   RootPanel.get("slot2").add(output);
   }
}
 

62/6<123456>
重磅发布,2022软件测试行业现状调查报告~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号