Unit Testing RAP Applications

February 22, 2013 | 3 min Read

The latest release of RAP 2.0 is still hot. It also contains some improvements for unit testing as Ralf Sternberg mentioned in one of his blog posts that came along with RAP 2.0. The following post will get you up and running with the first JUnit test in your own RAP project.

A user interface written with RAP is executed on the server side. This requires you to abstract from the execution environment in your test code. RAP supports you with a so-called test fixture to do so. The test fixture thus enables your test code to run without any server infrastructure.

Disclaimer: Although the test fixture comes with the official RAP 2.0 target it is not officially supported API. There is work underway to improve the mechanisms currently provided by the test fixture. This means that the test fixture’s API will change in the future. Please keep this in mind. Nevertheless this post explains the way in which to write unit test for RAP 2.0.

Create the UI

As a simple example the class MyComposite should create a new composite with two buttons on it. Let’s take a look at a basic test that ensures your MyComposite is created as expected.

public class MyComposite_Test {

  private Display display;

  @Before
  protected void setUp() throws Exception {
    Fixture.setUp();
    display = new Display();
  }

  @After
  protected void tearDown() throws Exception {
    Fixture.tearDown();
  }

  @Test
  public void testCompositeHasTwoChildren() {
    MyComposite myComposite = new MyComposite( display );

    assertEquals(2, myComposite.getChildren().length);
  }
}

As you can see in the setUp() and tearDown() methods, the Fixture provides a convenient way to prepare the environment so your actual UI manipulation in testCompositeHasTwoChildren() will just work. It’s as simple as this to write you first test.

Event Handling

Next to the creation of your UI you most probably want to test that your event handling does the right thing. In RAP, event handling happens in a special phase. The test fixture allows you to set the phase so your test can correctly trigger events. Let’s assume you registered a ModifyListener on a Text widget. Now your test could ensure the correct listener is invoked and behaves as expected by writing a test like this:

// setUp and tearDown as in example above

@Test
public void testModifyingTextShouldTriggerXY() {
  Fixture.fakePhase(PhaseId.PROCESS_ACTION);
  // prepare Text widget

  text.setText(""); // triggers event

  // assert ModifyListener did the right thing
}

Conclusion

Writing unit tests for your RAP application’s UI code is easy with help of the test fixture. This post explained the fundamental steps to write such tests. If you have any questions regarding unit testing RAP applications or using one of the other features provided by the test fixture, please comment below.