A simple unit test for GUIs

Part 2: Server envy


So here's what you end up with: one Panel class, one Controller class, one UI interface, and at least one Test class that contains its own minimal implementation of the UI interface as an inner class. The diagram, courtesy of the rather nice, Linux-based Umbrello UML Modeller, shows how it all fits together.

Each Panel class has one Controller class and one UI interface, at runtime each Panel instance has one Controller instance, and the Controller itself is where the data lives - the instance of a Customer bean.

I've assembled some example Swing code here. In the example, the Customer ID is validated if you press Enter or try to close the JFrame; it'll refuse to close if the ID isn't between one and 10 characters. Remember, this is just an example and you’ll be better served by something like JGoodies Validation Framework for "real" form validation.

And that's really all there is to it. No great mystery. Swing GUIs are not difficult to unit test! Sure, you could spend time grappling with GUI testing frameworks that provide questionable extensions to JUnit, but really - seriously - there's no need, as long as you keep a constant focus on good design principles.

As an added bonus, this approach also provides a roadmap towards distributing your objects. The separate controller classes could be "remoted" - turned into web services, for example. What you're then doing is creating a distributed service, which is much more useful than individual distributed objects.

Of course, separating the application/business logic from the GUI code doesn't automatically make a system "remotable". Issues of latency, security and caching will remain to be contended with, but it is a step in the right direction, as it opens up an approach that previously - with logic tightly wound into the GUI code - just wouldn't have been available. ®

Agile Iconoclast Matt Stephens has co-authored Use Case Driven Object Modeling with UML: Theory and Practice, which explores ways to drive functional tests and unit tests from use cases.


Other stories you might like

Biting the hand that feeds IT © 1998–2022