I am using asp.net mvc application with NUnit test project (dotnet framwork).
I am trying to test SomeController method which is inheriting from BaseController.
In BaseController , there is a parameter less constructor which read configuration, open db connection, writing logs etc.
When i do unit test of one of method in SomeController its keep calling BaseController constructor.
I wanted to mock BaseController so that its constructor not get called.
I tried mocking BaseController but not sure how the same used with SomeController as mocked base class.
The project i am working is existing one without code coverage. Now we started doing that.
How to resolve this ? Waiting for answers and alternate approach ...


Jayraj ChhayaRank #304 · 8.2K reputationPosted Nov 17, 2023, 8:19 AM EST
To prevent calling the base class constructor or mock it during unit testing, you can use the concept of dependency injection and create a mock object for the base class.
public interface IBaseController { // Define the methods and properties required by the base class // Example: void ReadConfiguration(); }public class BaseController : IBaseController { // Implement the methods and properties defined in the interface // Example: public void ReadConfiguration() { ... } }public class SomeController { private readonly IBaseController _baseController; public SomeController(IBaseController baseController) { _baseController = baseController; } // Use the methods and properties of the base class as needed // Example: _baseController.ReadConfiguration(); }var mockBaseController = new Mock(); // Setup the mock object as needed // Example: mockBaseController.Setup(x => x.ReadConfiguration()).Returns(...); var someController = new SomeController(mockBaseController.Object);By using dependency injection and mocking the base class, you can control the behavior of the base class during unit testing without actually calling its constructor. This approach allows you to isolate the functionality of the derived class and focus on testing its specific logic.
Alternatively, you can also consider refactoring the base class to separate the tasks performed in the constructor into separate methods. This way, you can selectively call these methods in the derived class or mock them during testing, depending on your requirements.