June 25, 2015
Mocks vs. Stubs - It Has Nothing To Do With The ImplementationAn area of confusion I see quite often is on the difference between mocking and stubbing.
I think this confusion arises from the frameworks we use to create mock objects, which can also be used to create stubs.
In practice, the difference is very straightforward.
If we want to test some logic that requires data that - for whatever reason - comes via a collaborator, we use a stub. Put simply, a stub returns test data.
If we want to test that an interaction with a collaborator happens the way we expect it should, we use a mock. Mock objects test interactions.
Take a look at these example tests, just to illustrate the difference more starkly:
The first test uses Mockito to create an object that returns test data, so I can test that the total cost of a trade is calculated correctly using the stock price my StockPricer stub returns.
The second test uses a hand-rolled object to test how many times the Trade object calls GetPrice() on the mock StockPricer.
Whether or not we used a mock objects framework has no bearing on whether the test double is a mock or a stub. The kind of test we're writing decides that.
If we want our test to fail because external data suppled by a collaborator was used incorrectly, it's a stub.
If we want our test to fail because a method was not invoked (correctly) on a collaborator, it's a mock.
(And, yes, back in the days before mock objects ,we'd have called MockStockPricer a "spy".)
Posted 3 years, 1 month ago on June 25, 2015