Gwt-junit-integration

提供:Dev Guides
移動先:案内検索

GWT-JUnit統合

GWTは、JUnitテストフレームワークを使用したクライアント側コードの自動テストの優れたサポートを提供します。 この記事では、GWTとJUNITの統合について説明します。

Junitアーカイブをダウンロードする

JUnit公式サイト-https://www.junit.org/[https://www.junit.org]

ダウンロード Junit-4.10.jar

OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar

ダウンロードしたjarファイルをコンピューター上のある場所に保管します。 C:/> JUNIT に保存しました

GWTインストールフォルダーを見つける

OS GWT installation folder
Windows C:\GWT\gwt-2.1.0
Linux /usr/local/GWT/gwt-2.1.0
Mac /Library/GWT/gwt-2.1.0

GWTTestCaseクラス

GWTは、JUnit統合を提供する GWTTestCase 基本クラスを提供します。 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.finddevguides.HelloWorld

注目すべきポイント

  • webAppCreatorコマンドラインユーティリティを実行しています。
  • HelloWorldは、作成するプロジェクトの名前です
  • -junitオプションはwebAppCreatorにjunitサポートをプロジェクトに追加するよう指示します
  • com.finddevguides.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\finddevguides
Created directory HelloWorld\src\com\finddevguides\client
Created directory HelloWorld\src\com\finddevguides\server
Created directory HelloWorld\src\com\finddevguides\shared
Created directory HelloWorld\test\com\finddevguides
Created directory HelloWorld\test\com\finddevguides\client
Created file HelloWorld\src\com\finddevguides\HelloWorld.gwt.xml
Created file HelloWorld\war\HelloWorldl
Created file HelloWorld\war\HelloWorld.css
Created file HelloWorld\war\WEB-INF\web.xml
Created file HelloWorld\src\com\finddevguides\client\HelloWorld.java
Created file
HelloWorld\src\com\finddevguides\client\GreetingService.java
Created file
HelloWorld\src\com\finddevguides\client\GreetingServiceAsync.java
Created file
HelloWorld\src\com\finddevguides\server\GreetingServiceImpl.java
Created file HelloWorld\src\com\finddevguides\shared\FieldVerifier.java
Created file HelloWorld\build.xml
Created file HelloWorld\README.txt
Created file HelloWorld\test\com\finddevguides\HelloWorldJUnit.gwt.xml
Created file HelloWorld\test\com\finddevguides\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.finddevguides.client;

import com.finddevguides.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.finddevguides.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. Note
1 HelloWorldTest class was generated in the com.finddevguides.client package under the HelloWorld/test directory.
2 HelloWorldTest class will contain unit test cases for HelloWorld.
3 HelloWorldTest class extends the GWTTestCase class in the com.google.gwt.junit.client package.
4 HelloWorldTest class has an abstract method (getModuleName) that must return the name of the GWT module. For HelloWorld, this is com.finddevguides.HelloWorldJUnit.
5 HelloWorldTest class is generated with two sample test cases testFieldVerifier, testSimple. We’ve added testGreetingService.
6 These methods use one of the many assert* functions that it inherits from the JUnit Assert class, which is an ancestor of GWTTestCase.
7 The assertTrue(boolean) function asserts that the boolean argument passed in evaluates to true. If not, the test will fail when run in JUnit.

GWT-JUnit統合の完全な例

この例では、簡単な手順でGWTでのJUnit統合の例を示します。

上記で作成したGWTアプリケーションを更新するには、次の手順に従います-

Step Description
1 Import the project with a name HelloWorld in eclipse using import existing project wizard (File → Import → General → Existing Projects into workspace).
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、Eclipseのプロジェクト構造です。

プロジェクト構造

以下は、変更されたモジュール記述子 src/com.finddevguides/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.finddevguides.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/HelloWorldl の内容です。

<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.finddevguides/client* パッケージのHelloWorld.javaの内容を次のように置き換えます
package com.finddevguides.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.finddevguides/client* パッケージのHelloWorldTest.javaの内容を以下で置き換えます
package com.finddevguides.client;

import com.finddevguides.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.finddevguides.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結果

実稼働モードでJUnitテストを実行する

  • Eclipseメニューバーから、[実行]→[実行構成…​]を選択します。
  • JUnitセクションで、HelloWorldTest-prodを選択します
  • 引数への変更を保存するには、適用を押します
  • テストを実行するには、実行を押します

すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT Junit結果