Testing software: fake vs stub

Viewed 11616

There are quite a few written about stub vs mocks, but I can't see the real difference between fake and stub. Can anyone put some light on it?

4 Answers

To paraphrase Roy Osherove in his book The Art of Unit Testing (second edition):

A Fake is any object made to imitate another object. Fakes can be used either as stubs or mocks.

A Stub is a fake that is provided to the class you are testing to satisfy its requirements, but is otherwise ignored in the unit test.

A Mock is a fake that is provided to the class you are testing, and will be inspected as part of the unit test to verify functionality.

For example, the MyClass class you are testing may utilize both a local logger and a third-party web service as part of its operation. You would create a FakeLogger and a FakeWebService, but how they are used determines whether they are stubs or mocks.

The FakeLogger might be used as a stub: it is provided to MyClass and pretends to be a logger, but actually ignores all input and is otherwise just there to get MyClass to operate normally. You don't actually check FakeLogger in your unit tests, and as far as you're concerned it's there to make the compiler shut up.

The FakeWebService might be used as a mock: you provide it to MyClass, and in one of your units tests you call MyClass.Foo() which is supposed to call the third party web service. To verify that this happened, you now check your FakeWebService to see if it recorded the call that it was supposed to receive.

Note that either of these could be reversed and depend on what it is you're testing in a particular unit test. If your unit test is testing the content of what is being logged then you could make a FakeLogger that dutifully records everything it's told so you can interrogate it during the unit test; this is now a mock. In the same test you might not care about when the third-party web service is called; your FakeWebService is now a stub. How you fill in the functions of your fake thus depends on whether it needs to be used as a stub or a mock or both.

In summary (direct quote from the book):

A fake is a generic term that can be used to describe either a stub or a mock object because they both look like the real object. . . . The basic difference is that stubs can't fail tests. Mocks can.

All the rest is implementation details.

Related