Thursday, June 2, 2011

Test: Testing with mock objects

Introducing mock objects
Testing in isolation offers strong benefits, such as the ability to test code that has not yet been written (as long as you at least have an interface to work with). In addition, testing in isolation helps teams unit test one part of the code without waiting for all the other parts.
The biggest advantage is the ability to write focused tests that test only a single method, without side effects resulting from other objects being called from the method under test. Small is beautiful. Writing small, focused tests is a tremendous help; small tests are easy to understand and don’t break when other parts of the code are changed.
Remember that one of the benefits of having a suite of unit tests is the courage it gives you to refactor mercilessly — the unit tests act as a safeguard against regression.
If you have large tests and your refactoring introduces a bug, several tests will fail; that result will tell you that there’s a bug somewhere, but you won’t know where. With fine-grained tests, potentially fewer tests will be affected, and they’ll provide precise messages that pinpoint the exact cause of the breakage.
Mock objects (or 
 for short) are perfectly suited for testing a portion of code logic in isolation from the rest of the code. Mocks replace the objects with which your methods under test collaborate, offering a layer of isolation. In that sense, they’re similar to stubs. But this is where the similarity ends, because mocks don’t implement any logic: 
they’re empty shells
 that provide methods to let the tests control the behavior of all the business methods of the faked class.

No comments :

Post a Comment