Unit Testing GWT Applications with JUnit

posted Sep 11, 2011, 3:53 AM by valerii ryzhuk   [ updated Sep 21, 2011, 9:10 AM ]

Unit Testing

1. Creating a JUnit test

package com.google.gwt.sample.stockwatcher.client; import com.google.gwt.junit.client.GWTTestCase; /** * GWT JUnit tests must extend GWTTestCase. */ public class StockWatcherTest extends GWTTestCase { /** * Must refer to a valid module that sources this class. */
  @Override public String getModuleName() { return "com.google.gwt.sample.stockwatcher.StockWatcher"; } /** * Add as many tests as you like. */ public void testSimple() { assertTrue(true); } }

Interesting: Module Name is com.google.gwt.sample.stockwatcher.StockWatcher. 
But this class is in com.google.gwt.sample.stockwatcher.client.StockWatcher.

    1. You must add standart JUnit4 libs to your project!!!
    2. When you run test in Eclipse you can see this Exception:
Exception in thread “main” java.lang.NoSuchMethodError: org.mortbay.thread.Timeout.<init>(Ljava/lang/Object;)V
at org.mortbay.io.nio.SelectorManager$SelectSet.<init>(SelectorManager.java:306)

I think the problem is an incompatibility between the Jetty in the GWT jars and the AppEngine jars.
I solved it by going into Properties->”Java Build Path”->”Order and Export” and then used “Up” to move the “GWT SDK” up above the “App Engine SDK”.

The normal use pattern is to setup an event in the test method and call delayTestFinish() with a timeout significantly longer than the event is expected to take. The event handler validates the event and then calls finishTest().


public void testTimer() {
// Setup an asynchronous event handler.
Timer timer = new Timer() {
public void run() {
// do some validation logic

// tell the test system the test is now done

// Set a delay period significantly longer than the
// event is expected to take.

// Schedule the event and return control to the test system.

3. Setting up and tearing down

The following example shows how to defensively cleanup the DOM before the next test
run using gwtSetUp(). It skips over <iframe> and <script> tags so that the GWT test 
infrastructure is not accidentally removed.

  import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

private static native String getNodeName(Element elem) /*-{
     return (elem.nodeName || "").toLowerCase();

   * Removes all elements in the body, except scripts and iframes.

public void gwtSetUp () {
Element bodyElem = RootPanel.getBodyElement();

List<Element> toRemove = new ArrayList<Element>();
for (int i = 0, n = DOM.getChildCount(bodyElem); i < n; ++i) {
Element elem = DOM.getChild(bodyElem, i);
String nodeName = getNodeName(elem);
if (!"script".equals(nodeName) && !"iframe".equals(nodeName)) {

for (int i = 0, n = toRemove.size(); i < n; ++i) {
.removeChild(bodyElem, toRemove.get(i));