text
stringlengths
0
13.4k
}
}
}
}
GoalKicker.com – .NET Framework Notes for Professionals
89
Chapter 26: Dependency Injection
Section 26.1: How Dependency Injection Makes Unit Testing
Easier
This builds on the previous example of the Greeter class which has two dependencies, IGreetingProvider and
IGreetingWriter.
The actual implementation of IGreetingProvider might retrieve a string from an API call or a database. The
implementation of IGreetingWriter might display the greeting in the console. But because Greeter has its
dependencies injected into its constructor, it's easy to write a unit test that injects mocked versions of those
interfaces. In real life we might use a framework like Moq, but in this case I'll write those mocked implementations.
public class TestGreetingProvider : IGreetingProvider
{
public const string TestGreeting = "Hello!";
public string GetGreeting()
{
return TestGreeting;
}
}
public class TestGreetingWriter : List<string>, IGreetingWriter
{
public void WriteGreeting(string greeting)
{
Add(greeting);
}
}
[TestClass]
public class GreeterTests
{
[TestMethod]
public void Greeter_WritesGreeting()
{
var greetingProvider = new TestGreetingProvider();
var greetingWriter = new TestGreetingWriter();
var greeter = new Greeter(greetingProvider, greetingWriter);
greeter.Greet();
Assert.AreEqual(greetingWriter[0], TestGreetingProvider.TestGreeting);
}
}
The behavior of IGreetingProvider and IGreetingWriter are not relevant to this test. We want to test that
Greeter gets a greeting and writes it. The design of Greeter (using dependency injection) allows us to inject mocked
dependencies without any complicated moving parts. All we're testing is that Greeter interacts with those
dependencies as we expect it to.
Section 26.2: Dependency Injection - Simple example
This class is called Greeter. Its responsibility is to output a greeting. It has two dependencies. It needs something
that will give it the greeting to output, and then it needs a way to output that greeting. Those dependencies are
both described as interfaces, IGreetingProvider and IGreetingWriter. In this example, those two dependencies
are "injected" into Greeter. (Further explanation following the example.)
GoalKicker.com – .NET Framework Notes for Professionals
90
public class Greeter
{
private readonly IGreetingProvider _greetingProvider;
private readonly IGreetingWriter _greetingWriter;
public Greeter(IGreetingProvider greetingProvider, IGreetingWriter greetingWriter)
{
_greetingProvider = greetingProvider;
_greetingWriter = greetingWriter;
}
public void Greet()
{
var greeting = _greetingProvider.GetGreeting();
_greetingWriter.WriteGreeting(greeting);
}
}