Thursday, July 23, 2009

Mocking Views

In my last post, I've shown how to implement a simple MVC over ASP.NET.

As you can see in the picture, every View implements an interface which exposes the events and methods of the View.

 

View

 

The Controller uses the View’s interface, so it is possible to mock the View in order to test the Controller without the aspx page running.

In the example of the last post, the View’s interface exposes these members:

 

internal interface ICustomersView
{
  event EventHandler<GenericEventArgs<string>> FindCustomer;
  void FillCustomers(IList<Customer> customers);
}

 

So, you can mock the View and raise the FindCustomer event this way (I am using the MOQ library):

Mock<ICustomerView> mock = new Mock<ICustomerView>();

CustomersController controller = new CustomersController(mock.Object);

mock.Raise(v => v.FindCustomer+= null,

                  new GenericEventArgs<string>(searchPattern));

0 comments: