ASP.NET Core Interview Question #73

How does dependency injection improve unit testing?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

DI makes dependencies replaceable. A class can be tested with a fake, stub, or mock implementation instead of connecting to a real database, external API, file system, or email provider.

Detailed Explanation

DI makes dependencies replaceable. A class can be tested with a fake, stub, or mock implementation instead of connecting to a real database, external API, file system, or email provider.

When business classes depend on small abstractions and receive them through constructors, tests can instantiate the class directly without starting the full ASP.NET Core host.

Good DI design does not automatically make code testable, but explicit dependencies and separated responsibilities make isolated testing substantially easier.

Code Example

public class OrderService
{
    private readonly IOrderRepository _repository;

    public OrderService(IOrderRepository repository)
    {
        _repository = repository;
    }
}

// Test can pass a fake repository:
// var service = new OrderService(fakeRepository);