Search code examples
asp.net.netasp.net-mvcvisual-studionunit

NUnit : How to prevent calling base class constructor or mocking base class constructor (ASP.NET MVC controller method testing with NUnit)


I am testing an ASP.NET MVC application with NUnit (on the .NET framework).

I am trying to test SomeController method which is inheriting from BaseController.

In BaseController, there is a parameterless constructor which read configuration, open db connection, writing logs etc.

When I do unit testing of one of method in SomeController, it keeps calling BaseController's constructor.

I wanted to mock BaseController so that its constructor is not getting called.

I tried mocking BaseController but not sure how the same used with SomeController as mocked base class.

How to resolve this? Waiting for answers and alternate approach ...


Solution

  • As Design Patterns recommend,

    Favor object composition over class inheritance.

    You are running into one of several problems with inheritance, as it's implemented in mainstream languages like C#. AFAIK, there's no direct resolution to that problem.

    Either change the base class so that its constructor doesn't do all of that implicit work (constructors should be simple), or don't inherit from BaseController.

    In the latter case, favour Constructor Injection instead of inheriting from a base class.

    public sealed class SomeController
    {
        private readonly ISomeDependency dep;
    
        public SomeController(ISomeDependency dep)
        {
            this.dep = dep;
        }
    
        // Use this.dep in methods...
    }
    

    This should enable you to test SomeController by supplying a Test Double of the dependency.