My posts from a couple years ago about building testable components for Google Web Toolkit with MVP are still fairly popular, they still drive a fair amount of traffic. GWT applications that I built in that era still use MVP, and while it certainly made those applications testable, the cost in boilerplate code and maintainability is high.
In the meantime, however, there were significant improvements in test frameworks that could disarm GWT widgets, making them testable without using the very slow GWTTestCase. If I were starting a new Google Web Toolkit application right now, I would be much more inclined to take this approach as the primary approach for building testable GWT applications.
Unsurprisingly, others have gone down this path. There's a pretty accessible presentation from Google I/O 2013 that talks about these different approaches for testing in GWT, Demystifying MVP and EventBus in GWT:
The first half of this presentation discusses some of the styles, the uses of MVP, and the alternative approach of building testable views by disarming the GWT widgets. It's pretty easy to follow, and in addition, the presentation briefly introduces gwtmockito, a framework for making it slightly easier to use mockito and GWT together for testable composite views.
While I haven't spent a lot of time with this approach and I haven't yet tried the framework, this matches very closely the path I would be inclined to explore with a new GWT application, so it feels like it's a step in the right direction at the very least.
If you're building applications in Google Web Toolkit, or considering a significant refactoring of an existing project, it's well worth watching.
Showing posts with label google web toolkit. Show all posts
Showing posts with label google web toolkit. Show all posts
Saturday, May 18, 2013
Tuesday, March 1, 2011
View-Presenter Interaction Patterns in Google Web Toolkit (GWT)
In Building Testable Applications in Google Web Toolkit (GWT), we talked about using the Model-View-Presenter (MVP) pattern. I also noted that there are different patterns, or styles of describing the interaction between the view and the presenter.
Let’s start with the example I’ve already used, a login form like this:

Your view has two text fields (username, password) and a button (login), as well as a few labels, possibly a title and some explanatory text. We’ll assume that the presenter needs to interact with the text fields and buttons, but that the labels, title and any explanatory text can be encapsulated into the view.
When you build your presenter, you’ll need to decide how the view and the presenter will interact, and there are a few approaches you can take.
So, for our example login view, we’ll need to expose the username, password and login button, and we can do so through interfaces already supported by these widgets. For instance, the
For our simple case, an abstracted control view would look like this:

This works well for simple cases, but quickly gets complicated. For instance, what if you want to expose an aspect of a control that doesn’t have a convenient interface, like
One alternative would have you create the interfaces that you need, extend GWT widgets and implement these interfaces. For instance, you could create

Since
This also gets complicated when you need to expose two or more aspects of one widget. For instance, if your login view chose to change the text on the login button to “logging in …” and disable it while the login process was underway, this requires you to expose three aspects of the login button — enable/disable, setting the text, and adding a click handler.
You can do this by grouping the interfaces you need to expose into interfaces that expose the exact right combination for a given view. You could build interfaces like like

While this gives you lots of control over the level of abstraction, and gives you a lot of substitutability (
Ultimately, if you end up exposing multiple aspects regularly, you’re probably better off accepting that it’s too awkward to maintain every combination of exposed aspects as a separate interface, and simply create an interface that combines all of the aspects you want to expose, either for each class, or for a cluster of related clsses. For instance, you might create a ‘TextInput’ interface that combines all the interfaces that you wish to expose on a

As an alternative, you could expose each aspect of a control through an independent accessor. Using the previous example, you could expose the login button control through independent methods that expose the enable/disable, text setting and click handling:

This style is fairly similar to the Interaction View style which follows; most people will find the Interaction View style more appealing.
For instance, although our login view has three controls, it has six known interactions:
Each of these can be exposed through a single method:

Alternately, you might choose to group the interactions if they’re likely to be invoked together:

This is closer to the approach used by Daniel Danilatos in GWT Testing Best Practices. If most of your controls expose a large number of unique aspects, this can get tedious — where an abstracted control view might need a single method per control, the interaction view might require several times that. Imagine a data-entry screen with twenty controls and complex behavior to show/hide fields, change styles, display field-level validation, and you'll start to see that this could get pretty messy. In practice, I find that relatively rare, but your mileage may vary depending on your project.
In addition, Interaction View tends to mesh well with mock testing, which is sometimes called Interaction-based testing, in that it allows the test to more clearly expect the intent, rather than needing to mock controls and expect certain messages to be passed to the controls.
In the case of our

This event delegate style fits most naturally as an extension of the Interaction View.
Let’s start with the example I’ve already used, a login form like this:

Your view has two text fields (username, password) and a button (login), as well as a few labels, possibly a title and some explanatory text. We’ll assume that the presenter needs to interact with the text fields and buttons, but that the labels, title and any explanatory text can be encapsulated into the view.
When you build your presenter, you’ll need to decide how the view and the presenter will interact, and there are a few approaches you can take.
Abstracted Control View
Ray Ryan’s Best Practices for Architecting your GWT App uses views that act as containers for controls. Rather than returning the widgets themselves (e.g.Anchor, Button, TextField), the views return interfaces that abstract the specifics of the control from the presenter. This allows the presenter to be completely decoupled from GWT widgets classes, as well as increasing your ability to substitute one control for another.So, for our example login view, we’ll need to expose the username, password and login button, and we can do so through interfaces already supported by these widgets. For instance, the
TextBox and PasswordTextBox widgets used for the username and password respectively implement the HasText interface, which would allow you to retrieve the text that has been entered, and the login button supports HasClickHandlers, which would allow you to add a ClickHandler event-handling class to the login button.For our simple case, an abstracted control view would look like this:

This works well for simple cases, but quickly gets complicated. For instance, what if you want to expose an aspect of a control that doesn’t have a convenient interface, like
setVisible(), which most GWT widgets inherit from UIObject, but which isn’t part of an interface.One alternative would have you create the interfaces that you need, extend GWT widgets and implement these interfaces. For instance, you could create
HasVisibility, then create a new class, VisibleAnchor which extends Anchor and implements HasVisibility:
Since
setVisible() comes from UIObject, each class that inherits from UIObject has the same consistent method signature, so as long as you’re willing to apply this subclassing approach pervasively, you can create the necessary interfaces.This also gets complicated when you need to expose two or more aspects of one widget. For instance, if your login view chose to change the text on the login button to “logging in …” and disable it while the login process was underway, this requires you to expose three aspects of the login button — enable/disable, setting the text, and adding a click handler.
You can do this by grouping the interfaces you need to expose into interfaces that expose the exact right combination for a given view. You could build interfaces like like
EnableableClickableText:
While this gives you lots of control over the level of abstraction, and gives you a lot of substitutability (
StyledText could be implemented by TextBox and Label while VisibleClickable could be implemented by Button and Anchor), this approach can quickly get out of control. On a project of any size, there are likely to be more combinations here than you care to count let alone implement.Ultimately, if you end up exposing multiple aspects regularly, you’re probably better off accepting that it’s too awkward to maintain every combination of exposed aspects as a separate interface, and simply create an interface that combines all of the aspects you want to expose, either for each class, or for a cluster of related clsses. For instance, you might create a ‘TextInput’ interface that combines all the interfaces that you wish to expose on a
TextField, and then create a TextInputBox class that extends TextInput and TextBox:
As an alternative, you could expose each aspect of a control through an independent accessor. Using the previous example, you could expose the login button control through independent methods that expose the enable/disable, text setting and click handling:

This style is fairly similar to the Interaction View style which follows; most people will find the Interaction View style more appealing.
Interaction View
Where the Abstracted Control View exposes abstractions of controls, the Interaction View exposes the interactions themselves.For instance, although our login view has three controls, it has six known interactions:
- get the username text
- get the password text
- add a click handler for the login button
- set the login button text
- disable the login button
- enable the login button
Each of these can be exposed through a single method:

Alternately, you might choose to group the interactions if they’re likely to be invoked together:

This is closer to the approach used by Daniel Danilatos in GWT Testing Best Practices. If most of your controls expose a large number of unique aspects, this can get tedious — where an abstracted control view might need a single method per control, the interaction view might require several times that. Imagine a data-entry screen with twenty controls and complex behavior to show/hide fields, change styles, display field-level validation, and you'll start to see that this could get pretty messy. In practice, I find that relatively rare, but your mileage may vary depending on your project.
In addition, Interaction View tends to mesh well with mock testing, which is sometimes called Interaction-based testing, in that it allows the test to more clearly expect the intent, rather than needing to mock controls and expect certain messages to be passed to the controls.
View Delegate
Finally, there’s the view delegate style, where the view handles the events, but delegates them to the presenter. This is of particular merit if you’re using GWT UiBinder and its support for@UiHandler to reduce boilerplate code, and can be seen in Large-Scale Application Development and MVP. In this model, the view will respond to the events of its controls, but delegate the processing of that event to the Presenter.In the case of our
LoginView, this is something you’d use for the login button click event:
This event delegate style fits most naturally as an extension of the Interaction View.
In Summary
If you’re writing a Google Web Toolkit (GWT) application and you’re using the model-view-presenter (MVP) pattern, you have some choices in terms of how you want your view and your presenter to interact. You can expose the controls through an abstraction layer, you can expose the interactions and you can optionally use a delegate approach, particularly if you’re using UiBinder with GWT 2.x.
tags:
development,
google web toolkit,
GWT,
model-view-presenter,
MVP,
patterns
Monday, January 17, 2011
Building Testable Applications with Google Web Toolkit
If you’re interested in developing web applications with Google Web Toolkit (GWT), and you’re used to writing applications with pervasive automated testing, you’re going to find that it isn’t always easy to build a testable application in GWT.
These are some of the challenges to automated testing in GWT.
GWT allows you to develop software in Java, but runs in a browser in Javascript. Most of the code that you write will be compiled from Java into Javascript, but parts of GWT itself and potentially some pieces of your code will simply be replaced by a Javascript equivalent, called using JSNI (JavaScript Native Interface). These pieces of code may rely on the capabilities of Javacript or the document-object model exposed by the browser.
For instance, if you were to attempt to match a regular expression against a String using Java, your Java code will use the Java implementation of regular expressions, but the final Javascript version will use Javascript’s regular expression capabilities. This can lead to subtle differences between behaviour the code that you tested and the final code that you’ll deploy, and even to behaviour from one browser to another.
Similarly, most of the GWT widgets are, at their core, tightly coupled to browser objects and events. As a result, they are not perfectly emulated in Java, and almost every GWT widget is built so that it cannot be easily constructed in Java — it will realize it’s not being run in Web Mode and throw an exception immediately. This makes it very difficult to use a simple JUnit test on widgets or on code that interacts directly with widgets.
Parts of the GWT development cycle aren’t terribly fast, particularly compilation. GWT is doing all sorts of great optimizations during compilation, but those optimizations come at a cost to development speed. That means that if you need to compile your application and launch it in order to test it, you might find that the test cycles are taking too long.
Even with those challenges in mind, you have options.
GWT explicitly supports automated testing through a test harness can you can use to load a unit of code within the GWT environment: GWTTestCase. This allows you to test your code thoroughly in an environment that is very similar to the one in which your code will be running ‘in production’, one which supports constructing and using GWT widgets directly.
That sounds like a pretty good setup, until you spend some time with it and discover that it’s very slow, a typical problem with integration testing. Due to the non-trivial nature of compiling your Java to Javascript and starting up the full testing environment, hosted browser and all, each test method might take twenty or more seconds. If you have 500 of these tests (which really isn’t that much for a test codebase), you could be talking about a test suite that takes over an hour and a half to complete.
GWTTestCase has a lot in common with integration testing; it’s slow because of the infrastructure required to do it, but the tests have the capability of being fairly thorough and cross-cutting if you’d like them to be. If you do want to do integration testing of your codebase, it may be the best option, since other integration testing tools are not always well-suited to AJAX-heavy applications.
As a result of the challenges posed by GWTTestCase, many people try and reduce their exposure to GWTTestCase by using it sparingly or not at all. GWTMockUtilities is intended to make it much easier to perform mock tests of classes that interact with GWT widgets. It does a few different things, the most important of which is to allow calls to
This allows you to write unit tests of code that interacts with GWT widgets in Java that run much more quickly than tests written using GWTTestCase. However, in order to allow you to mock all the widgets within a GWT view, you’ll need to write your user interface in a way that separates the widgets from the logic sufficiently that you can mock out all of the widgets being used. Isolating one piece of code from another is a very common problem in building testable code. This kind of test isolation can be encouraged using dependency injection, with or without a framework like Google GIN, and with patterns like the Model-View-Presenter pattern.
In Ray Ryan’s Best Practices for Architecting your GWT App at Google I/O 2009, he suggests reducing the view to something so simple that it doesn’t need to be tested. The display logic and code to connect your model to the controls can then be tested using JUnit rather than something like GWTTestCase, and those tests can be fast. He calls this Model-View-Presenter in reference to Martin Fowler’s article on the subject.
Martin Fowler has since sub-divided his MVP pattern into two possible implementation styles: Supervising Controller and Passive View. Supervising Controller puts all the event-processing logic and anything complex in the presenter, but allows the View to still perform simple data model bindings. Passive View takes on even those responsibilities, leaving the view to exist primarily as a composite set of user interface widgets. The Passive View style seems more in keeping with the approach Ray Ryan describes in his talk, although if you chose not to test data bindings, then Supervising Controller might be another approach worth considering.
By way of example, let’s imagine a simple login form that looks like this:

This might be represented by a view class like this:

And the presenter would listen for the click event of the button, then get the text from the username and password controls, attempt a login, and then update the view on the basis of the results of the login attempt:

While the Model-View-Presenter pattern can help you make better use of
Instead of having your presenter access a

In addition to allowing you to avoid the additional complexity of
Although GWT has a number of interfaces that you can expose, you’ll find there will be methods that you wish to expose that are not covered by an interface. For instance, if you need to change the styles associated with a widget, you’ll find that

You’ll also find that although granular interfaces communicate your intent most clearly and increase your ability to substitute implementations, they break down as your interaction between view and presenter increases. If you want to get/set the text of a control as well as adjust the styles, you either need to expose both HasText and your new HasStyle interface, or you need to combine them into a common HasTextAndStyle interface. You may quickly find that the number of combinations you need grows nearly without bounds, and that you’re better off introducing an interface for each widget that exposes all of the methods that you’re likely to invoke on that widget. You can do this with your own set of packages or with a nomenclature like
If you find yourself wanting to substitute one widget for another (see Liskov’s Substitution Principle), you may need a hierarchy of interfaces, possibly mirroring the hierarchy that GWT provides (UIObject, Widget, FocusWidget, etc.). The tradeoff between granular interfaces at the one end of the spectrum and monolithic ones at the other is awkward, and different teams are likely to take different positions on this point.
It’s worth noting that GWT Testing Best Practices at Google I/O encourages a slightly different style of integrating presenter event handlers with view widgets. Where Ray Ryan suggests:
Daniel Danilatos suggests:
I’ve used the former style in the above examples, but either approach is viable.
Passive View makes it possible to assemble complicated GWT user-interfaces and yet still test the bulk of the logic within the user interface. By turning the view into a simpler container for UI widgets, you create a very simple object which is hard to test, but for which automated testing would be of limited value.
The presenter takes on the responsibilities of moving data in and out of those widgets and reacting to events from the user or other parts of the application, and the presenter can be tested using standard Java testing frameworks which run quite quickly. At that point, the choice of testing framework and extensions (JUnit, TestNG, JMock, EasyMock, Mockito) is mostly a matter of taste.
Unfortunately, this kind of separation of the user interface widgets from all the logic that interacts with it has some costs. The view and the presenter are very tightly coupled and have lots of individual interactions. While the sequence diagram for the login view probably seemed reasonable, a complicated view might need to expose tens of widgets, or possibly a dynamic collection of widgets depending on how much information has been displayed on the screen. Each of those widgets may also have a relatively high number of interactions — setting and getting text values, adding and removing styles, showing and hiding the widget, adding click handlers, and so forth.
In an object-oriented application, you typically use encapsulation to contain complexity and reduce the number of external interactions by combining portions of the view into components with their own presentation logic. The Passive View approach can make encapsulation difficult and increase the number of external interactions. This is not simply a matter of design aesthetics — it also means that presenter tests can themselves be quite complicated and require quite a bit of painstaking mocking and stubbing. This may still be preferable to a glacial test suite, but it’s time-consuming and brittle.
If you’ve used other object-oriented user interface frameworks in Java, such as Tapestry or Wicket, you’ll find yourself wanting to encapsulate elements within your pages as components that bundle user interface widgets with logic. It’s certainly possible to do so, but well-encapsulated component that contains both logic and GWT widgets is no longer amenable to simple JUnit testing and you’ll have fall back to the
If you find that you need a complicated view, you might find some scenarios where a portion of the view can be isolated from GWT widgets and remain testable. GWT Testing Best Practices uses a good example where a view implements paging using a high-level view and two lower-level elements, one of which uses widgets and the other is a simple POJO storage model. The high-level view and POJO detail view remain testable, while the widget-detail view, which deals directly with GWT widgets, cannot easily be tested using a simple JUnit test. This sort of decomposition is only likely to work with larger, more-complex views, but it’s something to keep in mind.
There are times where you can develop a sort of hybrid model that allows you to encapsulate elements of the presenter logic into smaller classes which are themselves like miniature presenters but for a component rather than a view, which offer some of the benefits of both encapsulated code and testability, but it’s difficult to develop an approach that you can apply consistently in this vein.
Finally, you can mix these two strategies together, making a conscious decision about when you’d like to build encapsulated components that require slower testing approaches and when you’d like to achieve fast, testable presenter code that reduces your ability to encapsulate and makes for complicated test harnesses. For instance, you could test widget code, particularly custom widgets, using
There’s no silver bullet to writing testable applications in Google Web Toolkit. There are several common approaches, each with their own set of tradeoffs, and it’s likely that anyone wishing to build test-driven applications with GWT is going to have their own set of complaints, but forearmed with the knowledge of these approaches, you can reduce the pain that you experience while developing a well-tested GWT application.
These are some of the challenges to automated testing in GWT.
JSNI
GWT allows you to develop software in Java, but runs in a browser in Javascript. Most of the code that you write will be compiled from Java into Javascript, but parts of GWT itself and potentially some pieces of your code will simply be replaced by a Javascript equivalent, called using JSNI (JavaScript Native Interface). These pieces of code may rely on the capabilities of Javacript or the document-object model exposed by the browser.
For instance, if you were to attempt to match a regular expression against a String using Java, your Java code will use the Java implementation of regular expressions, but the final Javascript version will use Javascript’s regular expression capabilities. This can lead to subtle differences between behaviour the code that you tested and the final code that you’ll deploy, and even to behaviour from one browser to another.
Similarly, most of the GWT widgets are, at their core, tightly coupled to browser objects and events. As a result, they are not perfectly emulated in Java, and almost every GWT widget is built so that it cannot be easily constructed in Java — it will realize it’s not being run in Web Mode and throw an exception immediately. This makes it very difficult to use a simple JUnit test on widgets or on code that interacts directly with widgets.
GWT Compilation is Slow
Parts of the GWT development cycle aren’t terribly fast, particularly compilation. GWT is doing all sorts of great optimizations during compilation, but those optimizations come at a cost to development speed. That means that if you need to compile your application and launch it in order to test it, you might find that the test cycles are taking too long.
Even with those challenges in mind, you have options.
GWTTestCase
GWT explicitly supports automated testing through a test harness can you can use to load a unit of code within the GWT environment: GWTTestCase. This allows you to test your code thoroughly in an environment that is very similar to the one in which your code will be running ‘in production’, one which supports constructing and using GWT widgets directly.
That sounds like a pretty good setup, until you spend some time with it and discover that it’s very slow, a typical problem with integration testing. Due to the non-trivial nature of compiling your Java to Javascript and starting up the full testing environment, hosted browser and all, each test method might take twenty or more seconds. If you have 500 of these tests (which really isn’t that much for a test codebase), you could be talking about a test suite that takes over an hour and a half to complete.
GWTTestCase has a lot in common with integration testing; it’s slow because of the infrastructure required to do it, but the tests have the capability of being fairly thorough and cross-cutting if you’d like them to be. If you do want to do integration testing of your codebase, it may be the best option, since other integration testing tools are not always well-suited to AJAX-heavy applications.
GWTMockUtilities
As a result of the challenges posed by GWTTestCase, many people try and reduce their exposure to GWTTestCase by using it sparingly or not at all. GWTMockUtilities is intended to make it much easier to perform mock tests of classes that interact with GWT widgets. It does a few different things, the most important of which is to allow calls to
GWT.create to go through without throwing an exception. This allows you to write unit tests of code that interacts with GWT widgets in Java that run much more quickly than tests written using GWTTestCase. However, in order to allow you to mock all the widgets within a GWT view, you’ll need to write your user interface in a way that separates the widgets from the logic sufficiently that you can mock out all of the widgets being used. Isolating one piece of code from another is a very common problem in building testable code. This kind of test isolation can be encouraged using dependency injection, with or without a framework like Google GIN, and with patterns like the Model-View-Presenter pattern.
Model-View-Presenter
In Ray Ryan’s Best Practices for Architecting your GWT App at Google I/O 2009, he suggests reducing the view to something so simple that it doesn’t need to be tested. The display logic and code to connect your model to the controls can then be tested using JUnit rather than something like GWTTestCase, and those tests can be fast. He calls this Model-View-Presenter in reference to Martin Fowler’s article on the subject.
Martin Fowler has since sub-divided his MVP pattern into two possible implementation styles: Supervising Controller and Passive View. Supervising Controller puts all the event-processing logic and anything complex in the presenter, but allows the View to still perform simple data model bindings. Passive View takes on even those responsibilities, leaving the view to exist primarily as a composite set of user interface widgets. The Passive View style seems more in keeping with the approach Ray Ryan describes in his talk, although if you chose not to test data bindings, then Supervising Controller might be another approach worth considering.
By way of example, let’s imagine a simple login form that looks like this:

This might be represented by a view class like this:

And the presenter would listen for the click event of the button, then get the text from the username and password controls, attempt a login, and then update the view on the basis of the results of the login attempt:

Exposing Widgets through Interfaces
While the Model-View-Presenter pattern can help you make better use of
GWTMockUtilities, it’s also true that once you’ve established a clean separation of the view from the presenter, you can often skip GWTMockUtilities altogether by exposing interfaces that represent your widgets from within the view. Mocking interfaces is often a preferred approach, and this is the approach that Ray Ryan demonstrates in his presentation.Instead of having your presenter access a
Button from the view, it could access a control that implements HasClickHandlers. TextBox controls could be replaced with the HasText interface: 
In addition to allowing you to avoid the additional complexity of
GWTMockUtilities, this also reduces the coupling between view and presenter, allowing you to, for instance, replace a Button with an Image or an Anchor as long as it implements the same interface that you’re exposing.Although GWT has a number of interfaces that you can expose, you’ll find there will be methods that you wish to expose that are not covered by an interface. For instance, if you need to change the styles associated with a widget, you’ll find that
addStyleName and removeStyleName are not covered by a GWT interface. If you wish to follow this approach, you’ll find you need to introduce new interfaces to GWT, as follows:
You’ll also find that although granular interfaces communicate your intent most clearly and increase your ability to substitute implementations, they break down as your interaction between view and presenter increases. If you want to get/set the text of a control as well as adjust the styles, you either need to expose both HasText and your new HasStyle interface, or you need to combine them into a common HasTextAndStyle interface. You may quickly find that the number of combinations you need grows nearly without bounds, and that you’re better off introducing an interface for each widget that exposes all of the methods that you’re likely to invoke on that widget. You can do this with your own set of packages or with a nomenclature like
IButton for the Button interface. If you find yourself wanting to substitute one widget for another (see Liskov’s Substitution Principle), you may need a hierarchy of interfaces, possibly mirroring the hierarchy that GWT provides (UIObject, Widget, FocusWidget, etc.). The tradeoff between granular interfaces at the one end of the spectrum and monolithic ones at the other is awkward, and different teams are likely to take different positions on this point.
It’s worth noting that GWT Testing Best Practices at Google I/O encourages a slightly different style of integrating presenter event handlers with view widgets. Where Ray Ryan suggests:
getLogin().addClickHandler( loginHandler );Daniel Danilatos suggests:
setLoginHandler( loginHandler );I’ve used the former style in the above examples, but either approach is viable.
Passive View
Passive View makes it possible to assemble complicated GWT user-interfaces and yet still test the bulk of the logic within the user interface. By turning the view into a simpler container for UI widgets, you create a very simple object which is hard to test, but for which automated testing would be of limited value.
The presenter takes on the responsibilities of moving data in and out of those widgets and reacting to events from the user or other parts of the application, and the presenter can be tested using standard Java testing frameworks which run quite quickly. At that point, the choice of testing framework and extensions (JUnit, TestNG, JMock, EasyMock, Mockito) is mostly a matter of taste.
Unfortunately, this kind of separation of the user interface widgets from all the logic that interacts with it has some costs. The view and the presenter are very tightly coupled and have lots of individual interactions. While the sequence diagram for the login view probably seemed reasonable, a complicated view might need to expose tens of widgets, or possibly a dynamic collection of widgets depending on how much information has been displayed on the screen. Each of those widgets may also have a relatively high number of interactions — setting and getting text values, adding and removing styles, showing and hiding the widget, adding click handlers, and so forth.
In an object-oriented application, you typically use encapsulation to contain complexity and reduce the number of external interactions by combining portions of the view into components with their own presentation logic. The Passive View approach can make encapsulation difficult and increase the number of external interactions. This is not simply a matter of design aesthetics — it also means that presenter tests can themselves be quite complicated and require quite a bit of painstaking mocking and stubbing. This may still be preferable to a glacial test suite, but it’s time-consuming and brittle.
If you’ve used other object-oriented user interface frameworks in Java, such as Tapestry or Wicket, you’ll find yourself wanting to encapsulate elements within your pages as components that bundle user interface widgets with logic. It’s certainly possible to do so, but well-encapsulated component that contains both logic and GWT widgets is no longer amenable to simple JUnit testing and you’ll have fall back to the
GWTTestCase approach. Achieving encapsulation often requires a parallel hierarchy of views and presenters at each level. Orchestrating and wiring these all can be challenging, but it’s still usually better than the alternatives.Decomposition for Testable Views
If you find that you need a complicated view, you might find some scenarios where a portion of the view can be isolated from GWT widgets and remain testable. GWT Testing Best Practices uses a good example where a view implements paging using a high-level view and two lower-level elements, one of which uses widgets and the other is a simple POJO storage model. The high-level view and POJO detail view remain testable, while the widget-detail view, which deals directly with GWT widgets, cannot easily be tested using a simple JUnit test. This sort of decomposition is only likely to work with larger, more-complex views, but it’s something to keep in mind.
Combining MVP and GWTTestCase
There are times where you can develop a sort of hybrid model that allows you to encapsulate elements of the presenter logic into smaller classes which are themselves like miniature presenters but for a component rather than a view, which offer some of the benefits of both encapsulated code and testability, but it’s difficult to develop an approach that you can apply consistently in this vein.
Finally, you can mix these two strategies together, making a conscious decision about when you’d like to build encapsulated components that require slower testing approaches and when you’d like to achieve fast, testable presenter code that reduces your ability to encapsulate and makes for complicated test harnesses. For instance, you could test widget code, particularly custom widgets, using
GWTTestCase but use Passive Views and test your presenters using JUnit and Mockito or JMock.In Summary
There’s no silver bullet to writing testable applications in Google Web Toolkit. There are several common approaches, each with their own set of tradeoffs, and it’s likely that anyone wishing to build test-driven applications with GWT is going to have their own set of complaints, but forearmed with the knowledge of these approaches, you can reduce the pain that you experience while developing a well-tested GWT application.
tags:
development,
google web toolkit,
GWT,
testing
Subscribe to:
Posts (Atom)