Advertisement
Advanced ASP.NET Core, Dependency Injection

How would you unit test a service or minimal API handler that depends on multiple injected interfaces, without spinning up the full DI container?

Short answer

Unit tests typically construct the class or call the handler function directly, passing mock or fake implementations of its dependencies (created via a mocking library like Moq or NSubstitute) directly as constructor or parameter arguments -- bypassing the DI container entirely…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Unit tests typically construct the class or call the handler function directly, passing mock or fake implementations of its dependencies (created via a mocking library like Moq or NSubstitute) directly as constructor or parameter arguments -- bypassing the DI container entirely, since unit tests should test the logic in isolation, reserving the real DI container's wiring behavior for integration tests using WebApplicationFactory.
[Fact]
public async Task ProcessOrder_SendsConfirmationEmail() {
    var mockEmailSender = new Mock<IEmailSender>();
    var sut = new OrderService(mockEmailSender.Object);  // direct construction, no DI container

    await sut.ProcessOrderAsync(new Order());

    mockEmailSender.Verify(e => e.SendAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
Real-world example
A test suite for OrderService directly constructs it with a mocked IEmailSender, verifying business logic behavior in milliseconds without any DI container overhead or network/database dependencies.
Likely follow-ups
  • When would an integration test actually need to resolve services through the real DI container?
  • How do you test a minimal API handler function that takes many injected parameters?
Related topics