I just finished reading the MVC 3.0 book and was wondering about the best way to Unit Test the MVC controllers. IoC seems to be the recommended way of doing this but how would that work with the business object factory methods? Should we be using a viewmodel to decouple the model from the controller? Ideally it would be as easy to use as the dataaccess unit testing solution. Has anyone tried implementing this?
You can create an IBoFactory interface. An instance of this interface can be mocked for your unit tests, and and real implementation would just be a wrapper to call the static methods.
We already have the IViewModel interface which would likely work well enough for this case. I could override the default constuctor and pass in my business object filled with mock data. But how do I do that? Do I have different assemblies, one for real data and one for mock data that I point to as with the DataAccess approach? Or can I simply use a single ViewModel with the difference being the default parameterless constructor creates a real business object while another contructor accepts a business object as an argument? I am leaning towards this last approach. I'll be trying it out Monday.
I've created a ViewModel using the ViewModelBase class and use this to call my business objects static methods or use an injected object, for example.
var controller = new MyObjectController(new MyObjectViewModel(MyObjectItemList.Get()));
The problem I now have is with the following code in the Controller;
return View(); I get the following Error: Attempt by method 'WebApplication.Controllers.MyObjectController.List()' to access method 'System.Web.Mvc.Controller.View()' failed. There is no inner exception. Anyone else run into this?
Additional Info:
It appears as though the controller.Model is null. This is true even after setting the model to my business object. I am suspecting that my mock is not properly creating the httpContext of the controller.
This appears to be a bug in the Csla.Web.Mvc.Controller. When I replace the base class on my controller with the System.Web.Mvc.Controller I am able to assign my business object to the model and the test passes. This only happens during unit testing.
As this is a separate issue from my original post I am going to create a separate thread for it.
Copyright (c) Marimer LLC