Skip to main content

Posts

Showing posts with the label dependency injection

TDD and Mocking

In the  last post  we have discussed core principles of unit testing and TDD. In this post, we’ll walk through a simple example of how to use Moq  as mocking framework and Dependency Injection with NUnit in the context of Test-Driven Development (TDD) in C#. This combination allows for clean, maintainable tests by mocking dependencies and focusing on the behavior of the system under test. Imagine we have an application where we process payments through a PaymentService . This service depends on an external IPaymentGateway interface to make the actual payment.  Let’s break this down step by step. Step 1: Write the Test First (Before Code) We want to test the PaymentService , which depends on the IPaymentGateway . Our first test will focus on making sure the PaymentService behaves correctly when making a valid payment. Here's the test code: using Moq; using NUnit.Framework; [TestFixture] public class PaymentServiceTests { private Mock<IPaymentGateway>...

Dependency Injection In .NET Core With Strategy Pattern

In the previous post, we gave an introduction and explained the basic concept of the  Strategy Pattern . Now, we want to go a bit further and demonstrate how it works in practice alongside a dependency injection in .NET Core. Instead of manually instantiating strategies, we let the ASP.NET Core DI container inject the correct implementation at runtime. Example For the showing purposes, let us asume that we are implementing some payment service, and we want to use one service at the time, depending on user input. For our strategy pattern, we would need following components: Interface public interface IPaymentStrategy { void Pay ( decimal amount ) ; } Concrete Strategies public class CreditCardPayment : IPaymentStrategy { public void Pay(decimal amount) { Console.WriteLine($"Paid ${amount} using Credit Card."); } } public class PayPalPayment : IPaymentStrategy { public void Pay(decimal amount) { Console.WriteLine($"Paid ${amoun...