What Is Dependency Injection (With Examples)
Here is a class you cannot unit test without a live database and a working SMTP server: 1 2 3 4 5 6 7 8 9 10 11 public class OrderService { private readonly SqlOrderRepository _repository = new SqlOrderRepository("Server=prod-db;Database=Orders;..."); private readonly SmtpEmailSender _emailSender = new SmtpEmailSender("smtp.company.com"); public void PlaceOrder(Order order) { _repository.Save(order); _emailSender.Send(order.CustomerEmail, "Order confirmed"); } } OrderService builds its own SqlOrderRepository and SmtpEmailSender with new, connection string and all. Every test that touches PlaceOrder needs a real Orders database and a real mail server, or it fails before your assertion runs. The logic you want to test is two lines: save the order, send the confirmation. It’s welded to two concrete classes you can’t swap out. ...