JUnit Integration

GWT includes a special GWTTestCase base class that provides JUnit integration. Running your GWTTestCase derived class launches an invisible browser that your test runs inside of.

You can run your test in either hosted mode or web mode. In hosted mode (the default), your test cases run as bytecode in a JVM. To test in web mode as compiled JavaScript, define the system property gwt.hybrid by passing in "-Dgwt.hybrid" as a JVM argument.

Creating a Test Case

GWT includes a handy junitCreator tool that will generate a starter test case for you, plus scripts for testing in both hosted mode and web mode. But here are the steps if you want to set it up by hand:

  1. Define a class that extends GWTTestCase.
  2. Create a module that inherits com.google.gwt.junit.JUnit and whose test subdirectory contains your class.
  3. Implement the method GWTTestCase.getModuleName() to return the fully-qualified name of the module you created above.
  4. When running the test case, make sure that your classpath contains
    • your project's src directory
    • your project's bin directory
    • gwt-user.jar
    • gwt-dev-windows.jar (or gwt-dev-linux.jar)
    • junit.jar

Example

Write a test case for FooTest.
public class FooTest extends GWTTestCase {

  /*
   * Specifies which module to use when running this test case. Must refer
   * to a valid module file that inherits com.google.gwt.junit.JUnit.
   * 
   * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
   */
  public String getModuleName() {
    return "com.example.foo.FooTest";
  }

  public void testStuff() {
    assertTrue(2 + 2 == 4);
  }
}
Create a com.example.foo.FooTest module.
 <module>
   <!-- Inherit the JUnit support -->
   <inherits name='com.google.gwt.junit.JUnit'/>
   <!-- Include client-side source we might like to test -->
   <source path="client"/>
   <!-- Include client-side source for the test cases -->
   <source path="test"/>
 </module>
 
The module doesn't declare an entry points; the JUnit module handles that.

Caveats

Tip
You don't need to create a separate module for every test case. In the example above, any test cases in com.example.foo.test (or any subpackage) can share the com.example.foo.FooTest module.