views:

454

answers:

1

I'm developing an asp.net (classic) application trying to implement the MVP pattern using this example. In trying to unit test my presenter and using the following pattern, the psuedocode for which looks like so

//base view interface
public interface IView
{
    event EventHandler Init;

    event EventHandler Load;

    bool IsPostBack { get; }

    void DataBind();

    bool IsValid { get;}
}

//presenter psuedo code
public class SomePresenter
{
     public SomePresenter(ISomeDomainService service, IView someView)
     {
           ...
           //HOW DO WE TEST/VERIFY THAT THIS REGISTRATION OCCURS?
           someView.Init += OnInit;
           someView.Load += OnLoad;
     }
}
...
//consuming code that exercises the above code, that needs to be tested
var presenter = new SomePresenter(someDomainService, someView);

How do I verify that the presenter is doing what is expected i.e. registering for the Init and Load events? While this is easily done in the Phil Haack's example using Rhino mocks...

[Test]
public void VerifyAttachesToViewEvents()
{
    viewMock.Load += null;
    LastCall.IgnoreArguments();
    viewMock.PostSaved += null;
    LastCall.IgnoreArguments();
    mocks.ReplayAll();
    new PostEditController(viewMock, 
      this.dataServiceMock);
    mocks.VerifyAll();
}

... how can we do this using MOQ?

+2  A: 

It would appear that this functionality is not currently available in moq, but may appear in a future version (I had a look in the 4.0.812.4 beta, but it doesn't seem to be there).

It may be worth asking the question, "why does SomePresenter need to subscribe to the View's Load and Init events?" Presumably it is because the SomePresenter class needs to respond to those events. So it might be better to use the Raise method on your Mock<IView> to raise the Load and Init events, and then assert that SomePresenter did the right thing in response to them.

Mark Heath
I thought about that, essentially there are two parts to testing this piece of code. 1. Interaction testing... that verifies event registration2. State based testing... which verifies that the event handler in the presenter behaves as expected.The clean unit test would be to test each of those cases separately. One solution for (1) is to add a couple of methods to the IView interfacepublic interface IView{ ... public void RegisterForInit(EventHandler callback); ...}and modify the presenter constructor topublic SomePresenter(...){ ... someView.RegisterFoInit(OnInit);}
Dilip Krishnan
and it follows that you can't use Strict Mocks from MOQ if there are event subscriptions involved. (groan)
Gishu