Mid From PDF SOLID Design Patterns & SOLID

How do you mock dependencies in unit tests using DI?

  • Use mocking libraries like Moq, NSubstitute, or FakeItEasy.
  • Create mocks of interfaces and inject them into the class under test:
var mockRepo = new Mock<IProductRepository>();

mockRepo.Setup(repo => repo.GetAll()).Returns(new List<Product> {

... });

var service = new ProductService(mockRepo.Object);

// Act & Assert

  • This allows testing in isolation without hitting real databases or external services.

More from Design Patterns in C#

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details