I have been using unit testing for controllers with the ‘poor man’s’ dependency injection technique. Each controller inherits from a base controller to query data for the master page. How do I unit test the controller with it inheriting from base controller without hitting the database?
public class HomeController : BaseController { IUserRepository _userRepository; public HomeController() : this(new UserRepository()) { } public HomeController(IUserRepository userRepository) { _userRepository = userRepository; } } public class BaseController : Controller { protected override void Execute(System.Web.Routing.RequestContext requestContext) { MyDataContext db = new MyDataContext(); ViewData['masterPageData'] = db.GetSomeData(); base.Execute(requestContext); } }
Code would look something like this:
That said, if you use a DI framework, you would only need 1 constructor in each class. So you can see how it starts leaning towards using one :).