C# – How to mockup a base controller in asp.net mvc

asp.netasp.net-mvccnetunit testing

I have a base controller that I made so I can pass data to the master page view easily. However this base controller gets a service layer passed into it and everything time I run my unit tests this service layer kills it since it tries to access some database stuff.

  private ServiceLayer service;

        public ApplicationController():this(new ServiceLayer())
        {
        }

        public PlannerApplicationController(IServiceLayer serviceS)
        {
            service= serviceS;           
        }

        protected override void Initialize(RequestContext requestContext)
        {

            base.Initialize(requestContext);
          // some stuff gets called here.
        }

First thing the service layer calls

   public ServiceLayer ()
            : this(new Repository())
        {

        }

// have another constructor for DI.

So when I run my tests and it goes to my controller that inherits this base controller once it hits my controllers constructor it seems to call this base controller.

So in my unit tests I tried to mock up the base controller by doing something like this

baseController = new ApplicationController(SerivceLayerInterface);

I using moq and stuff to mock up the repository in the serviceLayer interface but it seems to have no effect.

So not sure what to do.

Best Answer

Instead of mocking up your base controller, why don't you mock up the service layer interface. For example, using MoQ you can do this:

var serviceMock = new Mock<IServiceLayer>();
//serviceMock.Setup(s => s.SomeMethodCall()).Returns(someObject);
var controller = new BaseController(serviceMock.Object);

The general idea is if you're testing your controller, you want to mock its dependencies. You want to avoid mocking the very thing you are testing.