10.4. Testing MVP Applications

The main advantage to following the MVP pattern is that it makes your application easy to test. To test an MVP application, you create a simulated or test version of your View interface. The Presenter then interacts with the simulated View rather than the actual View implementation. You can add additional infrastructure code to the simulated View that allows you to simulate user interactions from your test code.

To test the sample application, you would write a simulated View such as the following. Note that this is the first example View that calls the Presenter directly.

class TestSurveyView : ISurveyView
     {
         List<string> users;
         bool question1;
         string question2;

         //get the back reference to the
         //presenter to events can be reported
         public TestSurveyView()
         {
             presenter = SurveyPresenter.Instance(this);
         }

         //the presenter reference
         SurveyPresenter presenter;

         //to be called by test code
         public void DoOnLoad()
         {
             presenter.OnLoad();
         }

         //to be called by test code
         public void ChangeSelection(int selectedIndex)
         {
             presenter.SelectedIndexChanged(selectedIndex);
         }

         #region ISurveyView Members

         public List<string> Users
         {
             get
             {
return users;
             }
             set
             {
                 users = value;
             }
         }

         public bool Question1
         {
             get
             {
                 return question1;
             }
             set
             {
                 question1 = value;
             }
         }

         public string Question2
         {
             get
             {
                 return question2;
             }
             set
             {
                 question2 = value;
             }
         }

         #endregion
     }

The extra methods DoOnLoad() and ChangeSelection() allow the test code to fire events that simulate user interaction. No user interface ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.