Testing with Mock Objects

Mock objects are useful when performing unit testing and can provide a best solution in terms of testability. I will present the new NMock 2.0 (Release Candidate 1) library and show how you can use it to implement mock objects.

Mock objects are used as abstractions for dependencies of a class under test and are used to effectively isolate the class under test to ensure proper test verification. For example, if Class A uses a class that is an abstraction for a network service, I don’t want to have to go through the effort of setting up a connection and verifying connectivity just to be able to test. Therefore, I create a mock for the other class, and define how it should behave. I then write my tests for Class A based on the expected behavior of the dependency. This effectively decouples a class from its dependencies and makes the entire development and testing process much more smooth.

A mock object is a testing pattern that is used to test interfaces rather than specific implementations of classes. This is done by defining the expectations of the methods of those classes, and then verifying that your expectations were met after calling the methods. This can be useful for classes that are not yet developed, difficult to setup for testing, or dependent on an external resource such as a database or web service, or for classes that perform prohibitively slowly, such that the execution time for the unit tests using the actual implementation would be too great.

Read more at: Developer.com