Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to focus on the code being tested and not on the behavior or state of external dependencies. In mocking, the dependencies are replaced by closely controlled replacements objects that simulate the behavior of the real ones. There are three main types of replacement objects - stubs, fakes and mocks.
Fakes: Fakes replace the actual code by implementing the same interface but without interacting with other objects. The problem Fakes introduce is they are hard coded to return fixed results and in order to test for different use cases a lot of Fakes must be introduced. Tests become hard to understand and maintain since the tests require a lot of Fakes as well as “else” statements to cover all possible statements.
Stubs: Stubs are similar to Fakes because they return prerecorded answers to calls. However, the difference is that by using a mocking framework you can create the Stub in the test with a minimal amount of code. Thus, it becomes clear how the dependency will respond and how the tested system should behave.
Mocks: Mocks have all the advantages of Stubs but also provide the option to specify behavior by setting an expectation on how many times a method must be executed. While Stubs are simple substitutes, Mocks are substitutes that can verify usage.
For more information on the differences between stubs, fakes and mocks read the Fakes, Stubs and Mocks blog post.
More practical examples on how to get started mocking can be found in the Doing Your First Mock blog post