Geeks With Blogs
Moot Points Chronicles of a Software Engineer.

With modern frameworks available that were built with loose coupling and separation of concerns in mind, working in WinForms may seem like a testability wasteland. But there are times when the options of WPF with MVVM or MVC on the web are not available, and you’re stuck with WinForms. But fear not, the Mode-View-Presenter pattern is here to save the day!

If you are not familiar with the MVP pattern, the idea is that you have a presenter, which handles all the interactions between the user and the model. The presenter “Talks” to the UI through an abstraction. There are a couple ways of doing the MVP pattern. I’m going to explore the Passive View style, meaning all logic is taken out of the view and moved into the presenter. I’m not going to go into differences in the styles, but if you’re interested, Martin Fowler has in depth descriptions of the Passive View, and Supervising Controller patterns, which are both derivatives of MVP.

I’m going to do a walkthrough for creating a simple MVP application. We need a premise for our demo. I’ll go with something simple, an application that organizes notes. Here our note will be a bit of textual data with a title. Lets implement it.

The Model

We need the note and title, as well as created and last edited dates for tracking. We’ll want to validate our model; lets make sure we actually have a note, and I’m going to use files for storage, so we need to make sure we can use our title as a filename:

public class NoteCard
    [RegularExpression(@"^[_0-9a-zA-Z\s\-_]+$", ErrorMessage="Title cannot contain special characters.")]
    public string Title { get; set; }
    public string NoteText { get; set; }
    public DateTime? CreateDate { get; set; }
    public DateTime? EditDate { get; set; }

I also created a repository that will handle the persistence:

public interface INoteCardRepository
    IEnumerable<string> NoteCards { get; }

    NoteCard GetNote(string title);
    bool NoteExists(string title);
    void Save(NoteCard note);
    void Delete(NoteCard note);

So, we have a nice way to represent our notes, now we need a way to display it.

The View

Our main form has a file menu, a status bar for displaying the number of notes, a list of notes, and a display/edit area for a note.


Keep in mind, this form IS our view. We need to abstract away our view by creating an interface that defines the capabilities of our UI:

public interface IMainView
    event EventHandler NewNote;
    event EventHandler NoteSelected;
    event EventHandler SaveNote;
    event EventHandler DeleteNote;
    string SelectedNote { get; set; }
    string StatusText { get; set; }
    string Title { get; set; }
    void DisplayMessage(string title, string message);
    void ClearSelectedNote();
    void LoadNotes(IEnumerable<string> notes);
    void LoadNote(NoteCard note);
    NoteCard GetNote();

IMainView is a contract that defines the UI, we need to make sure our form fulfills that contract. Since we’re using the passive view style, the implementation will be vary anemic. The only job of MainForm will be translating the messages into UI actions (databinding, manipulating controls, etc.) and notifying interested parties (the presenter) of user interaction:

public partial class MainForm : Form, IMainView

The Presenter

Our presenter is going to be doing all the real work. So it will need access to the view and the repository. Since our goal here is loose coupling, we’re going to inject those dependencies via the constructor:

public MainPresenter(IMainView view, INoteCardRepository repository)

We now have enough to write our first test. So lets pause here and write a test before we implement the constructor. To mock the dependencies I’m using Moq.

public void LoadTest()
    var notes = new[] {"Note1", "Note2"};
    var repo = new Mock<INoteCardRepository>();
    var view = new Mock<IMainView>();
    repo.Setup(m => m.NoteCards)
    var presenter = new MainPresenter(view.Object, repo.Object);
    view.Verify(m => m.LoadNotes(It.IsAny<IEnumerable<string>>()));
    view.VerifySet(m => m.StatusText = "2 Notes");

We're testing what happens when the application starts. Don’t worry if you’re unfamiliar with Moq, just understand that the test is making sure the the note list gets loaded and the status gets updated upon loading. But I highly recommend checking out the quickstart and familiarizing yourself with Moq.

Now that we have a presenter, lets fill in the constructor and make the test pass:

_view = view;
_repository = repository;
view.NewNote += NewNote;
view.NoteSelected += NoteSelected;
view.SaveNote += SaveNote;
view.DeleteNote += DeleteNote;
var notes = _repository.NoteCards.ToList();

_view.StatusText = String.Format("{0} Notes", notes.Count);

We’re loading the notes, setting the status, so now our tests pass. And in the real implementation the application works as expected. You’ll also notice we’re wiring up events. This is so we can get notified when the user does something we care about. Lets take a look at one of the handlers:

private void NewNote(object sender, EventArgs e)
    _view.LoadNote(new NoteCard());

As you can see, all we’re doing here is clearing the selection, and loading a blank note. We could easily write a test for this too by using Moq’s RaiseEvent method.


Now we have an application that is loosely coupled, largely UI and persistence agnostic, and has well separated concerns. All the things that Engineers love and end users don’t care about. But users do care that an application works, so what we’ve really achieved is testability, which means (hopefully) software that works!

Check out the full sourcecode, which is available in my github NoteCards Repository. Now go write some code!

Posted on Tuesday, February 21, 2012 4:01 AM Patterns | Back to top

Comments on this post: WinForms and MVP: Making a testable application

# re: WinForms and MVP: Making a testable application
Requesting Gravatar...
Nice to see someone NOT creating the presenter in the view for once! Good example.
Left by Fen on Feb 27, 2012 4:10 AM

# re: WinForms and MVP: Making a testable application
Requesting Gravatar...
Great little write-up on MVP pattern and making for some testable UI. Going to be using this as a model for some work I'm doing.
Left by osumoogle on Jan 13, 2014 6:09 PM

# re: WinForms and MVP: Making a testable application
Requesting Gravatar...
nice article
Left by Dean on Jan 21, 2014 11:20 AM

# re: WinForms and MVP: Making a testable application
Requesting Gravatar...
Thanks! I like the idea creating the presenter out of the view.
Left by HoangITK on May 26, 2014 10:49 PM

# re: WinForms and MVP: Making a testable application
Requesting Gravatar...
great article, I'm going to start using it in my next project.
Left by Sandy Mena on Nov 08, 2015 8:25 AM

# re: WinForms and MVP: Making a testable application
Requesting Gravatar...
Thanks for this mate :D

Left by Derstine on Aug 23, 2017 12:28 PM

Your comment:
 (will show your gravatar)

Copyright © lennykean | Powered by: