Automated GUI Testing With Mocks
By Adrian Sutton
I’ve been developing some custom views (javax.swing.text.View subclasses) in the last few days. These are right up the alley of GUI code that people tend to find difficult to test but I’ve been pushing forward with test driven development with a fair bit of success. The main approach I’ve been using is to mock out pretty much everything the view interacts with and test it’s logic more than it’s actual rendering. In fact, this particular view doesn’t do any rendering of it’s own, but it does do a lot of layout of child views etc.
In fact, most View instances do a lot of layout work, interacting with the model, CSS styles, passing on event notifications and converting between view positions and model positions. There’s a lot of stuff you can test in there. The key problem is the number of mocks you wind up having to create for a View.
For instance, I’ve currently got a mock child view, mock parent view, mock element, mock document and mock stylesheet. That’s a lot of mocks. Fortunately, you can push them all down into a common super-class that is used for testing all your views so there’s a lot of reuse, but it can be hard to keep straight what everything should be doing. The advantage of this effort though is that views are exceptionally complex to write, so having tests describing how they should interact and ensuring that all the right notifications are sent etc is invaluable when it comes to making changes.
On the down side, TDD doesn’t guarantee you’ll cover every case and I seem to have missed an important interaction as deleting content will every so often cause a stream of exceptions. I’ll have to look into that first thing Monday morning – sorry to those using our internal wiki in the mean time. If you switch to code view and back things straighten themselves out again.