DECOUPLING WITH MOCK OBJECTS
A well-written piece of software tries to limit dependencies. There comes a point, however, where each of your components must be coupled with another to form a greater whole. These couplings create a web of dependencies within your application that usually end in an external resource, be it a database, web service, file system, or other resource. Mock objects are designed to stand in for these other components in your application and the external resources they sometimes represent. This allows you to test your code without having to worry about the consequences of interacting with other resources.
Why Mocking Is Important
When you write unit tests for a method, your intention is to test only the code in that method. This is by design; you are attempting to isolate the code under test. The reason for this is that you want to assess the validity of only that piece of code for a given condition. A condition can be defined as not only the input data for that method, but also the context and environment that the code will execute in.
By isolating that code, you can ensure that any failing tests point squarely to a problem with that specific method, not a method in a far-flung corner of the system. For this example, it's okay to assume that the other components your method works with are correct and have been tested themselves and that you can rely on the quality of these components and tests. (I'll talk more about dealing with third-party components 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.