Tuesday, August 16, 2011

Rhino Mocks:

Rhino Mocks is a dynamic mock object framework for the .Net platform. Its purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing.


What is a mocked object?


Mock objects take stubs to an extreme and are used to set and verify expectations on interactions with model code



The need for mock objects:
A Mock Object:
  1. is easily created
  2. is easily set up
  3. is quick
  4. is deterministic
  5. has easily caused behavior
  6. has no direct user interface
  7. is directly queriable
You may want to use a Mock Object if the:
  1. real object has non-deterministic behavior
  2. real object is difficult to set up
  3. real object has behavior that is hard to cause (e.g., network error) (similar to 1)
  4. real object is slow
  5. real object has (or is) a UI
  6. test needs to query the object, but the queries are not available in the real object (e.g., "was this callback called?") (This needs a Mock Object that has *more* stuff than the real object; the other cases usually require a stub that is far smaller than the real object).
  7. real object acts "normal" most of the time, but once a month (or even less often) it does something "exceptional". We want Unit Tests to make sure the rest of the system does the Right Thing whether or not the object is acting "normal" or "exceptional". (Is this the same as #2 ?)
  8. real object does not yet exist
Mock objects are used in Unit Testing to isolate tests. Mock Objects allows you to test just the specific class / method without testing (and setting up, and tearing down, etc) the entire environment. Here is a simple example of using mock objects:



Benefits of Mocking:
  • Recognized testing pattern
  • Encourage passing objects as method parameters rather than making references to them part of our object state.
  • Mock objects tend to drive your classes into a highly compositional design with lots of little pieces and lots of interface surface
  • Encourage lightweight classes and more flexible methods.

No comments:

Post a Comment