English 中文(简体)
GWT - JUnit Integration
  • 时间:2024-09-17

GWT - JUnit Integration


Previous Page Next Page  

GWT provides execellent support for automated testing of cpent side code using JUnit testing framework. In this article we ll demonstrate GWT and JUNIT integration.

Download Junit archive

JUnit Official Site − https://www.junit.org

Download Junit-4.10.jar

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

Store the downloaded jar file to some location on your computer. We ve stored it at C:/ > JUNIT

Locate GWT installation folder

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

GWTTestCase Class

GWT provides GWTTestCase base class which provides JUnit integration. Running a compiled class which extends GWTTestCase under JUnit launches the HtmlUnit browser which serves to emulate your apppcation behavior during test execution.

GWTTestCase is a derived class from JUnit s TestCase and it can be run using JUnit TestRunner.

Using webAppCreator

GWT provides a special command pne tool webAppCreator which can generate a starter test case for us, plus ant targets and ecppse launch configs for testing in both development mode and production mode.

Open command prompt and go to C: > GWT_WORKSPACE > where you want to create a new project with test support.Run the following command

C:GWT_WORKSPACE>C:GWTgwt-2.1.0webAppCreator 
   -out HelloWorld 
   -junit C:JUNITjunit-4.10.jar 
   com.tutorialspoint.HelloWorld

Noteworthy Points

    We are executing webAppCreator command pne utipty.

    HelloWorld is the name of the project to be created

    -junit option instructs webAppCreator to add junit suppport to project

    com.tutorialspoint.HelloWorld is the name of the module

Verify the output.

Created directory HelloWorldsrc
Created directory HelloWorldwar
Created directory HelloWorldwarWEB-INF
Created directory HelloWorldwarWEB-INFpb
Created directory HelloWorldsrccom	utorialspoint
Created directory HelloWorldsrccom	utorialspointcpent
Created directory HelloWorldsrccom	utorialspointserver
Created directory HelloWorldsrccom	utorialspointshared
Created directory HelloWorld	estcom	utorialspoint
Created directory HelloWorld	estcom	utorialspointcpent
Created file HelloWorldsrccom	utorialspointHelloWorld.gwt.xml
Created file HelloWorldwarHelloWorld.html
Created file HelloWorldwarHelloWorld.css
Created file HelloWorldwarWEB-INFweb.xml
Created file HelloWorldsrccom	utorialspointcpentHelloWorld.java
Created file 
HelloWorldsrccom	utorialspointcpentGreetingService.java
Created file 
HelloWorldsrccom	utorialspointcpentGreetingServiceAsync.java
Created file 
HelloWorldsrccom	utorialspointserverGreetingServiceImpl.java
Created file HelloWorldsrccom	utorialspointsharedFieldVerifier.java
Created file HelloWorlduild.xml
Created file HelloWorldREADME.txt
Created file HelloWorld	estcom	utorialspointHelloWorldJUnit.gwt.xml
Created file HelloWorld	estcom	utorialspointcpentHelloWorldTest.java
Created file HelloWorld.project
Created file HelloWorld.classpath
Created file HelloWorldHelloWorld.launch
Created file HelloWorldHelloWorldTest-dev.launch
Created file HelloWorldHelloWorldTest-prod.launch

Understanding the test class: HelloWorldTest.java

package com.tutorialspoint.cpent;

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

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

   /**
    * must refer to a vapd module that sources this class.
    */
   pubpc String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }

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

   /**
    * this test will send a request to the server using the greetServer
    *  method in GreetingService and verify the response.
    */
   pubpc 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 pne 
       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>() {
         pubpc void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }

         pubpc 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();
         }
      });
   }
}

Noteworthy Points

Sr.No. Note
1 HelloWorldTest class was generated in the com.tutorialspoint.cpent 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.cpent package.
4 HelloWorldTest class has an abstract method (getModuleName) that must return the name of the GWT module. For HelloWorld, this is com.tutorialspoint.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 Integration Complete Example

This example will take you through simple steps to show example of JUnit Integration in GWT.

Follow the following steps to update the GWT apppcation we created above −

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

Following will be the project structure in ecppse.

Project Structure

Following is the content of the modified module descriptor 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.cpent.HelloWorld />
  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

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

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

Following is the content of the modified HTML host file war/HelloWorld.html.

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

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

Replace the contents of HelloWorld.java in src/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;

import com.google.gwt.core.cpent.GWT;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyUpEvent;
import com.google.gwt.event.dom.cpent.KeyUpHandler;

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

pubpc class HelloWorld implements EntryPoint {
	
   pubpc void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         pubpc 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("Cpck Me!");

      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent 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.setCellHorizontalApgnment(buttonMessage, 
      HasHorizontalApgnment.ALIGN_RIGHT);

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

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

Replace the contents of HelloWorldTest.java in test/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

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

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

   /**
    * must refer to a vapd module that sources this class.
    */
   pubpc String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }

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

   /**
      * this test will send a request to the server using the greetServer
      *  method in GreetingService and verify the response.
   */
   pubpc 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 pne 
       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>() {
         pubpc void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }

         pubpc 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.
      */
      pubpc void testGetGreeting() {
         HelloWorld helloWorld = new HelloWorld();
         String name = "Robert";
         String expectedGreeting = "Hello "+name+"!";
         assertEquals(expectedGreeting,helloWorld.getGreeting(name));
      }
   }
}

Run test cases in Ecppse using generated launch configurations

We ll run unit tests in Ecppse using the launch configurations generated by webAppCreator for both development mode and production mode.

Run the JUnit test in development mode

    From the Ecppse menu bar, select Run → Run Configurations...

    Under JUnit section, select HelloWorldTest-dev

    To save the changes to the Arguments, press Apply

    To run the test, press Run

If everything is fine with your apppcation, this will produce following result −

GWT Junit Results

Run the JUnit test in production mode

    From the Ecppse menu bar, select Run → Run Configurations...

    Under JUnit section, select HelloWorldTest-prod

    To save the changes to the Arguments, press Apply

    To run the test, press Run

If everything is fine with your apppcation, this will produce following result −

GWT Junit Results Advertisements