5

Mocking External Resources

WHAT'S IN THIS CHAPTER?

  • Why statically binding components creates brittle systems
  • How the dependency injection pattern can help you by dynamically binding these components
  • How a dependency injection framework can help you manage the dependencies within your application
  • How to effectively mock your application's data access code with the repository pattern

Most applications you'll write as a business application developer are composed of various components (some you'll create; others will come from a third party) that are combined to perform a task. Sometimes these components represent external resources, such as a database, a web service, a file system, or even a physical device. These external resources are required by the components in your application, yet you still need to be able to test the components in isolation, away from the external resources. Developers practicing TDD do this by providing stand-ins for these external resources at runtime. These stand-ins are called mocks.

To use mocks, and to truly isolate the individual components under test, you need an alternative to statically binding the individual components. The dependency injection pattern can be used to inject the concrete implementations of these components at runtime or during testing. Dependency injection frameworks help you manage the web of dependencies and ensure that the correct concrete implementation is provided based on the context your component is being used in. ...

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.