Mocks and Stubs - The difference is in the flow of information
Historical article · Originally published September 16, 2007; technical details may be outdated.
In class today when explaining the difference between stubs and mocks, I realized a simple explanation to this:
Stubs and mocks may seem the same but the flow of information from each is very different.
- Stubs provide input for the application under test so that the test can be performed on something else.
- Mocks provide input to the test to decide on pass\fail. the opposite direction.
The following diagram shows the flow of critical information:
The red arrows signify the "critical" flow of information that is used to decide if the test had passed. A stub can never fail a test, so there is no flow of information back to the test. the mock records things and then tells our test if it's expectations have been met according to its recording.
A stub is application facing, and a mock is test facing. Here's a more in depth overview of the two, but I haven't seen this explained as I just did anywhere. It's important to know and distinguish the two since many frameworks for mocking use these terms for different kinds of objects.
Lessons on this topic
- Introduction to Hand Written Fakes, Mocks and Stubs · The Art of Unit Testing & TDD Master Class in .NET
- Terminology · The Art of Unit Testing and TDD in Java
- Summary Day 1 · TDD in .NET in Hebrew