title: Testing WinForms MVP and Event mechanism with moq
body: <p>I've been using MVP pattern in my application. But I have problems with testing my method which are called after button is clicked. Here is the code:</p>
  
  <pre><code>public interface IControl
      {
          bool Enabled { get; set; }
          string Text { get; set; }
      }
  
  public interface IButton : IControl
      {
          event EventHandler Click;
      }
  
  public class Button : System.Windows.Forms.Button, IButton
      { }
  
  public interface IForm : IControl
      {
          void Show();
          void Close();
      }
  
  public interface IView : IForm
      {
          IButton Button1 { get; }
      }
  
  public partial class View : Form, IView
      {
          public View()
          {
              InitializeComponent();
          }
  
          #region IView Members
  
          public IButton Button1
          {
              get { return button1; }
          }
  
          #endregion
      }
  
  public class Presenter
      {
          IView view;
  
          public Presenter(IView view)
          {
              this.view = view;
              this.view.Button1.Click += ButtonClick;
              this.view.Show();
          }
  
          private void ButtonClick(object sender, EventArgs e)
          {
              view.Button1.Text= "some text";
          }
      }
  </code></pre>
  
  <p>The problem is that I don't know how to write test so that my ButtonClick method get called. I tried like this:</p>
  
  <pre><code>var view = new Mock&lt;IView&gt;();
  view.Setup(x =&gt; x.Button1).Returns(new Mock&lt;IButton&gt;().SetupAllProperties().Object);
  Presenter presenter = new Presenter(view.Object);
  view.Raise(x =&gt; x.Button1.Click+= null, EventArgs.Empty);
  Assert.AreEqual("some text", view.Object.Button1.Text);
  </code></pre>
  
  <p>I think that problem is in this line:</p>
  
  <pre><code>this.view.Button1.Click += ButtonClick;
  </code></pre>
  
  <p>It seems that Click event doesn't remember ButtonClick method. How to make Click to be stub to work just normal.
  Any suggestion is welcome.
  Thanks in advance.
  Regards,
  Vajda</p>
  
  <p>EDIT: I was able to do that when I created SubscribeOnClick(EventHandler click); method in my IButton interface instead of event EventHandler Click. And I made some ButtonMock where I remembered method. But still, if someone knows for better solution, please share with me.</p>