Table of contents
1.
Introduction
2.
GWT JUnit Integration
2.1.
GWTTestCase Class
2.2.
Using webAppCreator
2.3.
GWT JUnit Integration Complete Example
3.
Frequently Asked Questions
3.1.
What is GWT?
3.2.
Why use GWT?
3.3.
What is code base?
3.4.
What is webAppCreator?
3.5.
What are the advantages of GWT?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

GWT JUnit Integration

Author Sanchit Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

As the code base changes, how can you make certain that you don’t break existing functionality? Unit testing is the answer. Creating a battery of good unit test cases is crucial to maintaining the quality of your application throughout its lifecycle.

GWT offers integration with the free and open-source JUnit testing framework to help you with your testing efforts. Unit tests that you can execute in both development and production modes will be possible to create.

In this article, we will see GWT and JUnit Integration.

GWT JUnit Integration

We can do automated testing of client-side code with the help of the JUnit testing framework. This excellent support for automated testing is provided by GWT.

Download the JUnit archive from JUnit Official Site or click here.

Let us store the downloaded jar file at C:\JUnit\

Locate the 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 Class

GWT offers the GWTTestCase base class, which integrates JUnit. The HtmlUnit browser is launched when a compiled class that extends GWTTestCase is run under JUnit. This browser mirrors the behaviour of your application while the test is running.

JUnit TestRunner can be used to execute GWTTestCase, a derived class of JUnit's TestCase.

Using webAppCreator

For testing in both development and production modes, GWT offers a unique command-line tool called webAppCreator that can produce a beginning test case for us together with ant targets and eclipse launch configs.

GWT WORKSPACE is where you want to build a new project with test support, so open the command prompt and navigate there.

Execute this command and verify the output

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


Output verification

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


Understanding the test class: Hello_WorldTest.java

package com.modulename.client;

import com.modulename.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 Hello_WorldTest extends GWTTestCase {


   /**
    * must refer to -> valid module that sources this class.
    */
   public String getModuleName() {
      return "com.modulename.Hello_WorldJUnit";
   }


   /**
    * 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 -> server using -> greetServer
    *  method in GreetingService and verify -> 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() 
      + "hello_world/greet");


      /* Need to wait for a response 
once this test function completes 
because RPC calls are asynchronous.
This line instructs the test runner to delay
timing out for up to 10 seconds. */
      delayTestFinish(10000);


      /* send a request to -> server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
            /* Unexpected error occurred as a result of the request.. */
            fail("Request failure: " + caught.getMessage());
         }


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


            /* As we have received a response, 
we must inform the test runner that 
the test is finished. You must call 
finishTest() after successful finishing 
of an asynchronous test, or the test 
will time out.*/
            finishTest();
         }
      });
   }
}
You can also try this code with Online Java Compiler
Run Code


Code Explanation - 

Here in this code, we tested the field using testFieldVerifier(). This test used the greetServer method of the GreetingService to send a request to the server and verify the response. After receiving the response, we told the test runner that the test was completed. So we called the finishTest() after the asynchronous test finished successfully. Otherwise, the test would have timed out.

GWT JUnit Integration Complete Example

This example will walk you through a few straightforward steps to demonstrate a JUnit Integration in GWT.

To update the GWT application we made before, take the next steps:

  1. Import the project with the name Hello_World in eclipse using import existing project wizard (File → Import → General → Existing Projects into workspace).
  2. Modify Hello_World.gwt.xml, Hello_World.css, Hello_World.html, and Hello_World.java. Keep the rest of the files unchanged.
  3. To validate the output of the implemented logic, compile and run the application.

 

Content of the modified module descriptor src/com.modulename/Hello_World.gwt.xml.


<?xml version = "1.0" encoding = "UTF-8"?>Hello_World
<module rename-to = 'hello_world'>
   <!-- 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.modulename.client.Hello_World'/>
  
   <!-- Specify the paths for translatable code    -->
   <source path = 'client'/>
   <source path = 'shared'/>


</module>


Content of the modified Style Sheet file war/Hello_World.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;
}


Content of the modified HTML host file war/Hello_World.html.

<html>
   <head>
      <title>Hello_World</title>
      <link rel = "stylesheet" href = "Hello_World.css"/>
      <script language = "javascript" src = "hello_world/hello_world.nocache.js">
      </script>
   </head>


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

 

Replace the contents of Hello_World.java in src/com.modulename/client package with the following

package com.modulename.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 Hello_World 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+"!";
   }
}
You can also try this code with Online Java Compiler
Run Code


Code Explanation - 

Here in this code, we created the User Interface. Then we defined values for  HorizontalPanel and VerticalPanel and added the widget to the root panel. In the end, we expected a string parameter name in getGreeting() for returning a value.

Replace the contents of Hello_WorldTest.java in test/com.modulename/client package with the following


package com.modulename.client;

import com.modulename.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 Hello_WorldTest extends GWTTestCase {


   /**
    * must refer to -> valid module that sources this class.
    */
   public String getModuleName() {
      return "com.modulename.Hello_WorldJUnit";
   }


   /**
    * 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 -> server using -> greetServer
    *  method in GreetingService and verify -> 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() 
      + "hello_world/greet");


      /* Need to wait for a response 
once this test function completes 
because RPC calls are asynchronous.
This line instructs the test runner to delay
timing out for up to 10 seconds. */
      delayTestFinish(10000);


      /* send a request to -> server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
            /* Unexpected error occurred as a result of the request.. */
            fail("Request failure: " + caught.getMessage());
         }


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


            /* As we have received a response, 
we must inform the test runner that 
the test is finished. You must call 
finishTest() after successful finishing 
of an asynchronous test, or the test 
will time out.*/
            finishTest();
         }
      });

      /**
         * tests ->getGreeting method.
      */
      public void testGetGreeting() {
         Hello_World hello_World = new Hello_World();
         String name = "Sanidhya";
         String expectedGreeting = "Hello "+name+"!";
         assertEquals(expectedGreeting,hello_World.getGreeting(name));
      }
   }
}
You can also try this code with Online Java Compiler
Run Code


Code Explanation - 

This code is an updated version of our previously written Hello_WorldTest.javaWe tested the getGreeting method, we set a value to name variable of string type to be used in expectedGreeting here in this code and as a parameter in getGreeting() in HelloWorld.java.

Using generated launch configurations, run test cases in Eclipse

Using the launch configurations produced by webAppCreator for both development mode and production mode, we'll run unit tests in Eclipse.


Run the JUnit test in development mode

  • Choose Run->Run Configurations from the Eclipse menu bar
  • Choose Hello_WorldTest-dev under the JUnit section
  • Press Apply to save the modifications to the Arguments
  • Press Run to run the test


If your application is functioning properly, this will result in the following:

Output

 

Run the JUnit test in production mode

Run the JUnit test in production mode

  • Select Run->Run Configurations from the Eclipse menu bar
  • Select Hello_WorldTest-prod under the JUnit section
  • Press Apply to save the modifications to the Arguments
  • Press Run to run the test


If your application is functioning properly, this will result in the following:

Output

Frequently Asked Questions

What is GWT?

Google Web Toolkit or GWT is a development toolkit used to build and optimize complex browser-based applications.

Why use GWT?

The GWT compiler optimizes the resulting code, removes dead code, and even obfuscates the JavaScript all at once.

What is code base?

A codebase is the entire body of source code for a specific software program or application.

What is webAppCreator?

A command-line tool that builds a starter application and scripts for starting development mode and compiling to JavaScript.

What are the advantages of GWT?

An open-source Java software development platform, Google Web Toolkit (GWT) makes it simple to create AJAX apps. You can use the Java development tools to create and debug AJAX apps with GWT.

Conclusion

In this article, we discussed GWT - JUnit Integration. We learned GWT - JUnit Integration with complete examples and how to run unit tests in both development and production modes.

You can refer to GWT's Developer Guide to learn more about GWT. The main ideas, resources, and libraries you'll use to create web applications with GWT are covered in this guide. Or, if you want to explore yourself, you can visit GWT's Official Website.

If you want to know about frameworks for Java, you may read our article 15 Best Java Frameworks To Use.

Check out JUnit Interview Questions here.

Nevertheless, you may consider our paid courses to give your career an edge over others.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Coding Ninjas
Live masterclass