I'm writing tests for controllers actions of ASP.Net Core application. All controllers of my app inherited from base controller, let's call it MyBaseController
. Constructor of this class looks like this:
public MyBaseController(ServiceA serviceA, ServiceB serviceB)
{
m_serviceA = serviceA;
m_serviceB = serviceB;
}
So any inherited class can be mocked with this:
protected TController MockedController<TController>() where TController: MyBaseController
{
var moqController = new Mock<TController>(serviceAMock, serviceBMock);
return moqController.Object;
}
This works fine until we have class which inherited from MyBaseController
and require ServiceC serviceC
additional argument.
When I tried to run tests for such controllers with extra arguments I've got an error: "Could not find a constructor that would match given arguments". Situation seems prety clear, but I have no idea how to write general costructor mock to avoid creation of specific methods for such classes (there are a lot of them with different constructor arguments).
Are any ways to achieve my goal? Or the best way is to write individual methods to mock classes with different arguments?
MockedController
method just wraps the constructor anyway, so you could get rid of that altogether. Unless there's something you've omitted?MyControllerBase
and replace some services for tests needs. Removing it is the last what I would do.Mock<TController>
in that case, to setup the methods?