Skip to content

Unit testing basics

Gael Lazzari edited this page Aug 23, 2012 · 13 revisions

Let's create a minimalist GWT view, which contains a button and a label.

UiBinder file:

<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui">
  <g:HTMLPanel>
    <g:Button ui:field="button">Display something</g:Button>
    <g:Label ui:field="label" />
  </g:HTMLPanel>
</ui:UiBinder> 

Java file:

public class SampleView extends Composite {

  interface SampleViewUiBinder extends UiBinder<Widget, SampleView> { }
  
  private static SampleViewUiBinder uiBinder = GWT.create(SampleViewUiBinder.class);
  
  @UiField
  Button button;
  
  @UiField
  Label label;
  
  public SampleView() {
    initWidget(uiBinder.createAndBindUi(this));
  }
  
  @UiHandler("button")
  void onClick(ClickEvent e) {
    label.setText("The button was clicked !");
  }
  
}

When the button is clicked, the label displays "The button was clicked !". Couldn't be simpler !

Now, we want to write a unit test to ensure that clicking the button will always display "The button was clicked !" in the label :

@GwtModule("com.googlecode.gwt.test.sample.Sample")
public class SampleViewTest extends GwtTest {
  
  @Test
  public void clickOnButtonShouldDisplayMessageInLabel() {
    // Arrange
    SampleView view = new SampleView();
    // ensure the label is visible and empty at init
    GwtAssertions.assertThat(view.label).isVisible().textEquals("");
    
    // Act : simule the click event
    Browser.click(view.button);
    
    // Assert: label should be visible and filled
    GwtAssertions.assertThat(view.label).isVisible().textEquals("The button was clicked !");
  }
}
  • The test class must extends GwtTest, which provides the mechanism to allow the instanciation of GWT components without any web server.

  • The Browser class provides some helpful methods to simulate user events, such as click, double-click, blur, etc.

  • TheGwtAssertions is an extension of fest-assert which provides fluent assertions for GWT widgets.