SUMMARY

Most applications you will write in your career as a business developer will rely on external resources of some sort. These could be databases, web services, file systems, or even pieces of physical equipment. In spite of this, you still need to ensure that the unit tests you write are isolated to exercise only the specific method you are testing independent of any dependencies. The traditional approach of statically creating these dependencies creates applications that are brittle and difficult to maintain.

The dependency injection pattern allows you to define these dependencies based on interfaces instead of concrete implementations. The concrete implementations of these interfaces can be provided, or injected, into the object at runtime. This enables you to vary the concrete implementation for these dependencies based on the context the object is being used in. At runtime your application can vary the concrete implementation based on the environment (Production, QA, Development). For unit testing you can inject mocked objects to stand in for actual implementations. This allows you to keep your tests isolated and predictable.

Accessing data is a very common requirement for business applications. Many developers have tried embedding the code to perform persistence actions in the actual class definitions themselves. This causes issues with data access code being distributed throughout the application and makes maintenance difficult.

By using the repository pattern, you ...

Get Professional Test-Driven Development with C#: Developing Real World Applications with TDD now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.