How to mock the base controller in asp.net mvc?

I have a basic controller that I made, so I can easily transfer data to view the main page. However, this base controller gets a service level into it, and all the time when I run my unit tests, this service level kills it because it is trying to access some database materials.

  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.
        }

Firstly, the level of service causes

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

        }

// has a different constructor for DI.

So when I run my tests and it goes to my controller, which inherits this base controller, when it gets into my controller constructor, it seems to call that base controller.

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

baseController = ApplicationController (SerivceLayerInterface);

moq , serviceLayer, , , .

, .

+3
1

, , . , MoQ, :

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

, , . , .

+3

Source: https://habr.com/ru/post/1719241/


All Articles