Wednesday, February 03, 2010

Fake: Stub vs. Mock

When you're writing unit tests, you'll occasionally find yourself in the situation where you need to create some kind of fake object and pass it into your object/method under test. What you do with that object next is what determines whether it's a mock object or just a stub. If your test makes an assertion on the fake (i.e. what methods were called on it, and with what arguments) then that fake is a mock object. If the test does not make any assertions on the fake, then it's just a stub.

In short:
all mocks are fakes
all stubs are fakes
no mock is a stub
no stub is a mock

Many so called "mocking frameworks" actually allow you to dynamically create both mocks and stubs, so it would be better to call them isolation frameworks as their primary function is to let you test your own objects in isolation by mocking/stubbing out external dependencies.

No comments: