4

Below is some code which is just the simplest MVP project I could make. How can I unit test the presenter using mock objects? Does a mock object mean a completely made up object? In this case, the presenter needs an instance of Form1, and Form1 inherits from the interface IForm1. Does that mean I need to create fake duplicates of Form1 and IForm1 that are used to unit test my presenter?

I feel like I'm really close to understanding what's going on here, I really want to get my head around unit testing an MVP model, I think it will be greatly beneficial for the system I'm working on.

Thanks!

using System;
using System.Windows.Forms;

namespace MVP_Testing {
    public partial class Form1 : Form, IForm1 {
        private Presenter p;
        public Form1() {
            InitializeComponent();
            p = new Presenter(this);
        }

        #region Interface
        public string Value1 {
            get { return inputValue1.Text; }
        }
        public string Value2 {
            get { return inputValue2.Text; }
        }
        public string Result {
            set { textBoxResult.Text = value; }
        }
        #endregion

        private void buttonCalculate_Click(object sender, EventArgs e) {
            p.DoCalculation();
        }
    }

    public interface IForm1 {
        string Value1 { get; }
        string Value2 { get; }
        string Result { set; }
    }

    public class Presenter {
        private readonly IForm1 _iform1;
        public Presenter(IForm1 iform1) {
            _iform1 = iform1;
        }

        public void DoCalculation() {
            int value1 = Convert.ToInt16(_iform1.Value1);
            int value2 = Convert.ToInt16(_iform1.Value2);
            _iform1.Result = (value1 * value2).ToString();
        }
    }
}
1
  • Excellent...I really loved it!
    – user6421
    Nov 26, 2013 at 13:35

1 Answer 1

3

To do the mocking you should use a mocking framework, there are plenty of good ones to choose from such as RhinoMock, Moq, this post on stack-overflow mentions all the good mocking frameworks. Choose one that best fits your needs.

The following example is how I would do this using RhinoMocks:

public void CorrectResult()
{
    //setup the mock object
    var mockedView = MockRepository.GenerateMock<IForm1>();
    mockedView.Expect(view => view.Value1).Return("2");
    mockedView.Expect(view => view.Value2).Return("3");

    //make the call to do the calculation
    var p = new Presenter(mockedView);
    p.DoCalculation();

    //check that the Result property was set to 6
    mockedView.AssertWasCalled(view => view.Result = "6");
}
1
  • Excellent example, this is super helpful thanks!
    – sooprise
    Jun 8, 2011 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.