GWT - JUnit 整合



GWT 使用 JUnit 測試框架為客戶端程式碼的自動化測試提供了優秀的支援。在本文中,我們將演示 GWT 和 JUNIT 的整合。

下載 Junit 壓縮包

JUnit 官方網站 − https://www.junit.org

下載 Junit-4.10.jar

作業系統 壓縮包名稱
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar

將下載的 jar 檔案儲存到計算機上的某個位置。我們將其儲存在 C:/ > JUNIT

找到 GWT 安裝資料夾

作業系統 GWT 安裝資料夾
Windows C:\GWT\gwt-2.1.0
Linux /usr/local/GWT/gwt-2.1.0
Mac /Library/GWT/gwt-2.1.0

GWTTestCase 類

GWT 提供了 GWTTestCase 基類,該類提供了 JUnit 整合。執行擴充套件 GWTTestCase 的已編譯類在 JUnit 下會啟動 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.tutorialspoint.HelloWorld

值得注意的點

  • 我們正在執行 webAppCreator 命令列實用程式。
  • HelloWorld 是要建立的專案名稱。
  • -junit 選項指示 webAppCreator 向專案新增 junit 支援。
  • com.tutorialspoint.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\tutorialspoint
Created directory HelloWorld\src\com\tutorialspoint\client
Created directory HelloWorld\src\com\tutorialspoint\server
Created directory HelloWorld\src\com\tutorialspoint\shared
Created directory HelloWorld\test\com\tutorialspoint
Created directory HelloWorld\test\com\tutorialspoint\client
Created file HelloWorld\src\com\tutorialspoint\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\tutorialspoint\client\HelloWorld.java
Created file 
HelloWorld\src\com\tutorialspoint\client\GreetingService.java
Created file 
HelloWorld\src\com\tutorialspoint\client\GreetingServiceAsync.java
Created file 
HelloWorld\src\com\tutorialspoint\server\GreetingServiceImpl.java
Created file HelloWorld\src\com\tutorialspoint\shared\FieldVerifier.java
Created file HelloWorld\build.xml
Created file HelloWorld\README.txt
Created file HelloWorld\test\com\tutorialspoint\HelloWorldJUnit.gwt.xml
Created file HelloWorld\test\com\tutorialspoint\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.tutorialspoint.client;

import com.tutorialspoint.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.tutorialspoint.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();
         }
      });
   }
}

值得注意的點

序號 說明
1 HelloWorldTest 類在 HelloWorld/test 目錄下的 com.tutorialspoint.client 包中生成。
2 HelloWorldTest 類將包含 HelloWorld 的單元測試用例。
3 HelloWorldTest 類擴充套件了 com.google.gwt.junit.client 包中的 GWTTestCase 類。
4 HelloWorldTest 類有一個抽象方法 (getModuleName),它必須返回 GWT 模組的名稱。對於 HelloWorld,這是 com.tutorialspoint.HelloWorldJUnit。
5 HelloWorldTest 類使用兩個示例測試用例 testFieldVerifier、testSimple 生成。我們添加了 testGreetingService。
6 這些方法使用從 JUnit Assert 類(它是 GWTTestCase 的祖先)繼承的眾多 assert* 函式之一。
7 assertTrue(boolean) 函式斷言傳入的布林引數計算結果為 true。如果不是,則在 JUnit 中執行時測試將失敗。

GWT - JUnit 整合完整示例

此示例將引導您完成簡單的步驟,以顯示 GWT 中 JUnit 整合的示例。

按照以下步驟更新我們上面建立的 GWT 應用程式:

步驟 描述
1 使用匯入現有專案嚮導(檔案→匯入→常規→將現有專案匯入工作區)在 eclipse 中匯入名為 _HelloWorld_ 的專案。
2 修改 _HelloWorld.gwt.xml_、_HelloWorld.css_、_HelloWorld.html_ 和 _HelloWorld.java_,如下所述。保留其餘檔案不變。
3 編譯並執行應用程式以驗證已實現邏輯的結果。

以下是 eclipse 中的專案結構。

Project Structure

以下是修改後的模組描述符 src/com.tutorialspoint/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.tutorialspoint.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.tutorialspoint/client 包中 HelloWorld.java 的內容替換為以下內容:

package com.tutorialspoint.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.tutorialspoint/client 包中 HelloWorldTest.java 的內容替換為以下內容:

package com.tutorialspoint.client;

import com.tutorialspoint.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.tutorialspoint.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 選單欄中,選擇執行→執行配置…
  • 在 JUnit 部分,選擇 HelloWorldTest-dev
  • 要儲存對引數的更改,請按應用
  • 要執行測試,請按執行

如果您的應用程式一切正常,這將產生以下結果:

GWT Junit Results

在生產模式下執行 JUnit 測試

  • 從 Eclipse 選單欄中,選擇執行→執行配置…
  • 在 JUnit 部分,選擇 HelloWorldTest-prod
  • 要儲存對引數的更改,請按應用
  • 要執行測試,請按執行

如果您的應用程式一切正常,這將產生以下結果:

GWT Junit Results
廣告