When I’m coaching teams in Test Driven Development (TDD), I’m often asked how to deal with the User Interface (UI). The problem is that the unit test frameworks are weak in testing Forms, Controls, Buttons, Grids, and so on. Weak because they do not support it at all or the tests become very fragile (e.g. renaming a Label causes the test to fail).
We address this problem with the Passive View Command pattern, PVC for short.
In this post, I’ll show you the basics on PVC. Following posts will explain the details.
The PVC pattern is a variation of the MVC (Model-View-Controller) or MVP (Model-View-Presenter) pattern for better testability.
The patter this is based on – Passive View – is described here.
The idea is to minimize the amount of code in the View. There should be no logic in the View but push a value onto a Control and pull it down from a Control. The sole purpose of the View is to define how the UI should look like.
The Presenter is responsible to map the data of the domain object model onto the view and to react to user input and act accordingly. All user interface logic is within the Presenter.
Commands represent action the presenter can execute on the Model: access data, save data, start operations and so on. A command is a bridge between the presenter (user interface logic) and the model (business logic). This allows to reduce the responsibility of the presenter to pure user interface logic. For example, the command defines the sequence of calls on the model, the transaction handling and exceptional behaviour.
The Model stands for all the rest: business logic, data, services and so on.
There are two main benefits of this pattern:
- separation of concerns
Each element (View, Presenter, Command, Model) has one single responsibility, as shown above. This separation of concerns leads to a better design regarding readability, flexibility and maintainability.
The main reason to use PVC is however the improved testability. The presenter, commands and model can be unit tested normally. Only the view containing the controls is hard to test. However, we do not test the view code with unit tests because there is only very little and simple code contained. The view is tested in system and acceptance tests.
Finally, because the only element not unit tested is the View, we can use Test Driven Development for all other elements, including the user interface logic in the Presenter. This results in a much higher test coverage as with other view design patterns.
That’s it for now. In the next PVC posts, I’ll show you details about the different elements.