Lesson 5
Managing Dependencies in TDD with C#
Introduction to Managing Dependencies in TDD

In previous lessons, we've explored the fundamentals of Test Driven Development (TDD), the Red-Green-Refactor cycle, and the setup of a testing environment using C#, and xUnit. Now, we shift our focus to a key aspect of TDD: managing dependencies. Managing dependencies ensures that each unit of your application can be tested in isolation, which is crucial in TDD for maintaining code reliability and robustness.

In this lesson, we will examine how to use interfaces for abstraction in C#, allowing us to manage dependencies effectively. Using simple examples, we will demonstrate how to apply the Red-Green-Refactor cycle in this context. We'll use C# with xUnit, a popular tool in testing, to provide practical context. Let’s dive in.

Understanding Dependencies and Interfaces

Dependencies in software development refer to the components or systems that a piece of code relies on to function properly. In the context of testing, dependencies can complicate unit tests because they might introduce external factors that affect the test outcomes. To ensure tests are isolated and independent, we use abstractions.

An interface in C# acts as a contract that defines the methods a class should implement. By programming against interfaces, you can easily swap out implementations, making code more modular and test-friendly.

For example, consider a logger that a component uses to record actions. By abstracting the logger as an interface, you decouple the component from a specific logging implementation. This abstraction allows you to replace the actual logger with a mock or fake when testing, thus focusing on testing the component, not its dependencies.

Implementing Interfaces in C#

We'll create a simple logger interface called ILogger to demonstrate dependency management. This interface will define a method Log, which our UserManager will use:

C#
1public interface ILogger 2{ 3 void Log(string message); 4}

The ILogger interface defines a single method Log that accepts a message of type string. The simplicity of this interface highlights the ease of creating test stubs or mocks to simulate logging during tests without invoking an actual logging mechanism.

Building the UserManager with Dependency Injection

Next, we build a UserManager class by using the ILogger interface. We utilize dependency injection to pass in a logger, illustrating how to maintain independence between the UserManager and any specific logging implementation.

C#
1public class UserManager 2{ 3 private readonly ILogger _logger; 4 private List<string> _users = new List<string>(); 5 6 public UserManager(ILogger logger) 7 { 8 _logger = logger; 9 } 10 11 public void AddUser(string username) 12 { 13 _users.Add(username); 14 _logger.Log($"User {username} added"); 15 } 16 17 public IEnumerable<string> GetUsers() 18 { 19 return _users; 20 } 21}

In UserManager, the logger is injected through the constructor, which allows you to provide different implementations of ILogger — such as a fake for testing or a real logger for production.

Testing with a Fake Logger

In testing, we use several different methods to simulate dependencies without relying on complex or unavailable implementations. We'll create a FakeLogger class to test the UserManager.

Here's how we do it:

C#
1using Xunit; 2using System.Collections.Generic; 3 4public class FakeLogger : ILogger 5{ 6 public List<string> Logs { get; } = new List<string>(); 7 8 public void Log(string message) 9 { 10 Logs.Add(message); 11 } 12} 13 14public class UserManagerTests 15{ 16 [Fact] 17 public void AddUser_AddsAValidUser() 18 { 19 var fakeLogger = new FakeLogger(); 20 var userManager = new UserManager(fakeLogger); 21 userManager.AddUser("john"); 22 Assert.Contains("john", userManager.GetUsers()); 23 } 24 25 [Fact] 26 public void AddUser_LogsWhenWeAddAUser() 27 { 28 var fakeLogger = new FakeLogger(); 29 var userManager = new UserManager(fakeLogger); 30 userManager.AddUser("john"); 31 Assert.Equal(new List<string> { "User john added" }, fakeLogger.Logs); 32 } 33}
TDD Workflow in Action
  • Red: We start by writing tests for UserManager. The first test checks if a user is added correctly, while the second test verifies that logging occurs.
  • Green: Implement UserManager to pass these tests, ensuring that both the user addition and logging functionalities work as expected.
  • Refactor: The current implementation is effective, although always look for opportunities to improve code readability and maintainability.
Summary and Preparation for Hands-on Practice

In this lesson, we covered how to manage dependencies in unit testing using interfaces and dependency injection in C#. We explored the use of fake objects to isolate components during tests. Here's a recap of the key points:

  • Abstract dependencies using interfaces to facilitate test isolation.
  • Implement dependency injection to pass dependencies like loggers.
  • Use a fake logger to simulate dependencies in unit tests.
  • Always apply the TDD cycle: Red - Write a failing test, Green - Implement minimal code to pass, Refactor - Optimize the code without changing its functionality.

In the following hands-on practice sessions, you will consolidate these concepts by applying them using TDD. Continue practicing to deepen your understanding and proficiency in TDD with C# and effective dependency management.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.