Is it necessary to mock all and every dependency in Unit Tests?

.net, c#, mocking, unit-testing

Solution

Well, you have to provide test doubles for all dependencies, not necessarily mocks.

Luckily,this is the 21st century and there are tools to make the job easier for us. You can use AutoFixture to create an instance of `OrderController` and inject mocks as necessary.

var fixture = new Fixture().Customize(new AutoConfiguredMoqCustomization());
var orderController = fixture.Create<OrderController>();

Which, basically, is equivalent to:

var factory = new Mock<IViewModelFactory>();
var repository = new Mock<INewsRepository>();
var delegateHelper = new Mock<IDelegateHelper >();
var customerContext = new Mock<ICustomerContextWrapper >();

var orderController = new OrderController(factory.Object, repository.Object, delegateHelper.Object, customerContext.Object);

If those dependencies depend on other types, those will be setup as well. AutoFixture with the `AutoConfiguredMoqCustomization` customization will build an entire graph of dependencies.

If you need access to, say, the repository mock, so you can do some additional setups or assertions on it later, you can freeze it. Freezing a type will make the `fixture` container contain only one instance of that type, e.g.:

var fixture = new Fixture().Customize(new AutoConfiguredMoqCustomization());
var repositoryMock = fixture.Freeze<Mock<INewsRepository>>();
repositoryMock.Setup(x => x.Retrieve()).Returns(1);

//the frozen instance will be injected here
var orderController = fixture.Create<OrderController>(); 

repositoryMock.Verify(x => x.Retrieve(), Times.Once);

I've used Moq in these examples, but AutoFixture also integrates with NSubstitute, RhinoMock and Foq.

Disclosure: I'm one of the project's contributors

Problem

I'm trying to create a unit test for an ASP.NET that has the following constructor definition (filled with Ninject when running the real application): ``` public OrderController(IViewModelFactory modelFactory, INewsRepository repository, ILoggedUserHelper loggedUserHelper, IDelegateHelper delegateHelper, ICustomerContextWrapper customerContext) { this.factory = modelFactory; this.loggedUserHelper = loggedUserHelper; this.delegateHelper = delegateHelper; this.customerContext = customerContext; } ``` I want to test the methods inside the OrderController class, but in order to isolate it, I have to mock all and every of those dependencies, which becomes outright ridiculous (having to also mock subdependencies probably). In this case, which is the best practice to Unit Test this class?

Original source