GWT - JUnit集成

GWT使用JUnit测试框架为客户端代码的自动化测试提供了出色的支持.在本文中,我们将演示GWT和JUNIT集成.

下载Junit存档

JUnit官方网站 :   https://www.junit.org

下载 Junit-4.10.jar

OS存档名称
Windowsjunit4.10.jar
Linuxjunit4.10.jar
Macjunit4.10.jar

将下载的jar文件存储到计算机上的某个位置.我们将它存储在 C:/> JUNIT

找到GWT安装文件夹

OSGWT安装文件夹
WindowsC:\ GWT \gwt-2.1.0
Linux/usr/local/GWT/gwt- 2.1.0
Mac/Library/GWT/gwt-2.1.0

GWTTestCase Class

GWT提供了 GWTTestCase 基类,它提供了JUnit集成.在JUnit下运行扩展GWTTestCase的编译类启动HtmlUnit浏览器,用于在测试执行期间模拟应用程序行为.

GWTTestCase是来自JUnit的TestCase的派生类,可以使用JUnit运行TestRunner.

使用webAppCreator

GWT提供了一个特殊的命令行工具 webAppCreator ,它可以为我们生成一个入门测试用例,加上ant目标和eclipse启动配置,用于在开发模式和生产模式下进行测试.

打开命令提示符并转到 C:\> GWT_WORKSPACE> 您要在其中创建具有测试支持的新项目.运行以下命令

C:\GWT_WORKSPACE>C:\GWT\gwt-2.1.0\webAppCreator 
   -out HelloWorld 
   -junit C:\JUNIT\junit-4.10.jar 
   com.it1352.HelloWorld

值得关注的点数

  • 我们正在执行webAppCreator命令行实用程序.

  • HelloWorld是要创建的项目的名称

  • -junit选项指示webAppCreator将junit suppport添加到项目

  • com.it1352.HelloWorld是模块的名称

验证输出.

Created directory HelloWorld\src
Created directory HelloWorld\war
Created directory HelloWorld\war\WEB-INF
Created directory HelloWorld\war\WEB-INF\lib
Created directory HelloWorld\src\com\it1352
Created directory HelloWorld\src\com\it1352\client
Created directory HelloWorld\src\com\it1352\server
Created directory HelloWorld\src\com\it1352\shared
Created directory HelloWorld\test\com\it1352
Created directory HelloWorld\test\com\it1352\client
Created file HelloWorld\src\com\it1352\HelloWorld.gwt.xml
Created file HelloWorld\war\HelloWorld.html
Created file HelloWorld\war\HelloWorld.css
Created file HelloWorld\war\WEB-INF\web.xml
Created file HelloWorld\src\com\it1352\client\HelloWorld.java
Created file 
HelloWorld\src\com\it1352\client\GreetingService.java
Created file 
HelloWorld\src\com\it1352\client\GreetingServiceAsync.java
Created file 
HelloWorld\src\com\it1352\server\GreetingServiceImpl.java
Created file HelloWorld\src\com\it1352\shared\FieldVerifier.java
Created file HelloWorld\build.xml
Created file HelloWorld\README.txt
Created file HelloWorld\test\com\it1352\HelloWorldJUnit.gwt.xml
Created file HelloWorld\test\com\it1352\client\HelloWorldTest.java
Created file HelloWorld\.project
Created file HelloWorld\.classpath
Created file HelloWorld\HelloWorld.launch
Created file HelloWorld\HelloWorldTest-dev.launch
Created file HelloWorld\HelloWorldTest-prod.launch

了解测试类:HelloWorldTest .java

package com.it1352.client;

import com.it1352.shared.FieldVerifier;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

/**
 * GWT JUnit tests must extend GWTTestCase.
 */
public class HelloWorldTest extends GWTTestCase {

   /**
    * must refer to a valid module that sources this class.
    */
   public String getModuleName() {
      return "com.it1352.HelloWorldJUnit";
   }

   /**
    * tests the FieldVerifier.
    */
   public void testFieldVerifier() {
      assertFalse(FieldVerifier.isValidName(null));
      assertFalse(FieldVerifier.isValidName(""));
      assertFalse(FieldVerifier.isValidName("a"));
      assertFalse(FieldVerifier.isValidName("ab"));
      assertFalse(FieldVerifier.isValidName("abc"));
      assertTrue(FieldVerifier.isValidName("abcd"));
   }

   /**
    * this test will send a request to the server using the greetServer
    *  method in GreetingService and verify the response.
    */
   public void testGreetingService() {
      /* create the service that we will test. */
      GreetingServiceAsync greetingService = 
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");

      /* since RPC calls are asynchronous, we will need to wait 
       for a response after this test method returns. This line 
       tells the test runner to wait up to 10 seconds 
       before timing out. */
      delayTestFinish(10000);

      /* send a request to the server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }

         public void onSuccess(String result) {
            /* verify that the response is correct. */
            assertTrue(result.startsWith("Hello, GWT User!"));

            /* now that we have received a response, we need to 
             tell the test runner that the test is complete. 
             You must call finishTest() after an asynchronous test 
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
   }
}

值得关注的点数

Sr.No.注意
1HelloWorldTest类是在HelloWorld/test目录下的com.it1352.client包中生成的.
2HelloWorldTest类将包含HelloWorld的单元测试用例.
3HelloWorldTest类扩展了GWTTestCase类com.google.gwt.junit.client包.
4HelloWorldTest类有一个抽象方法(getModuleName),它必须返回GWT模块的名称.对于HelloWorld,这是com.it1352.HelloWorldJUnit.
5HelloWorldTest类是使用两个示例测试用例testFieldVerifier,testSimple生成的.我们添加了testGreetingService.
6这些方法使用它继承自JUnit Assert类的许多assert *函数之一,该类是GWTTestCase的祖先.
7assertTrue(boolean)函数断言传入的boolean参数的计算结果为true.如果没有,在JUnit中运行时测试将失败.

GWT  -  JUnit集成完成示例

此示例将指导您完成在GWT中显示JUnit Integration示例的简单步骤.

按照以下步骤更新我们在上面创建的GWT应用程序 :

Step描述
1使用名称
2修改 HelloWorld.gwt.xml HelloWorld.css HelloWorld.html HelloWorld.java ,如下所述.保持其余文件不变.
3编译并运行应用程序以验证实现逻辑的结果.

以下将是eclipse中的项目结构.

项目结构

以下是修改后的模块描述符的内容 src/com.it1352/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.it1352.client.HelloWorld'/>
  
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下是修改后的样式表文件的内容 war/HelloWorld.css .

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下是修改过的HTML主机文件的内容 war/HelloWorld.html .

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>JUnit Integration Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

用以下替换 src/com.it1352/client包中的HelloWorld.java的内容b $ b

package com.it1352.client; 
import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {
	
   public void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Click Me!");

      buttonMessage.addClickHandler(new ClickHandler() {			
         @Override
         public void onClick(ClickEvent event) {
            Window.alert(getGreeting(txtName.getValue()));
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage, 
      HasHorizontalAlignment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }  
   
   public String getGreeting(String name){
      return "Hello "+name+"!";
   }
}

test/com.it1352/client包含以下内容

package com.it1352.client;

import com.it1352.shared.FieldVerifier;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

/**
 * GWT JUnit tests must extend GWTTestCase.
 */
public class HelloWorldTest extends GWTTestCase {

   /**
    * must refer to a valid module that sources this class.
    */
   public String getModuleName() {
      return "com.it1352.HelloWorldJUnit";
   }

   /**
    * tests the FieldVerifier.
    */
   public void testFieldVerifier() {
      assertFalse(FieldVerifier.isValidName(null));
      assertFalse(FieldVerifier.isValidName(""));
      assertFalse(FieldVerifier.isValidName("a"));
      assertFalse(FieldVerifier.isValidName("ab"));
      assertFalse(FieldVerifier.isValidName("abc"));
      assertTrue(FieldVerifier.isValidName("abcd"));
   }

   /**
      * this test will send a request to the server using the greetServer
      *  method in GreetingService and verify the response.
   */
   public void testGreetingService() {
      /* create the service that we will test. */
      GreetingServiceAsync greetingService = 
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");

      /* since RPC calls are asynchronous, we will need to wait 
       for a response after this test method returns. This line 
       tells the test runner to wait up to 10 seconds 
       before timing out. */
      delayTestFinish(10000);

      /* send a request to the server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }

         public void onSuccess(String result) {
            /* verify that the response is correct. */
            assertTrue(result.startsWith("Hello, GWT User!"));

            /* now that we have received a response, we need to 
             tell the test runner that the test is complete. 
             You must call finishTest() after an asynchronous test 
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
	
      /**
         * tests the getGreeting method.
      */
      public void testGetGreeting() {
         HelloWorld helloWorld = new HelloWorld();
         String name = "Robert";
         String expectedGreeting = "Hello "+name+"!";
         assertEquals(expectedGreeting,helloWorld.getGreeting(name));
      }
   }
}

使用生成的启动配置在Eclipse中运行测试用例

我们将使用webAppCreator为开发模式和生产模式生成的启动配置在Eclipse中运行单元测试.

在开发模式下运行JUnit测试

  • 从Eclipse菜单栏中选择Run → 运行配置...

  • 在JUnit部分下,选择HelloWorldTest-dev

  • 要将更改保存到参数,请按Apply

  • 要运行测试,请按Run

如果您的应用程序一切正常,这将产生以下结果 :

GWT Junit Results

在生产模式下运行JUnit测试

  • 从Eclipse菜单栏中选择Run → 运行配置...

  • 在JUnit部分下,选择HelloWorldTest-prod

  • 要将更改保存到参数,请按Apply

  • 要运行测试,请按Run

如果您的应用程序一切正常,这将产生以下结果 :

GWT Junit Results