Explain the difference between mocking and stubbing in the context of testing. When should you prefer one over the other?

.NET interview question for Intermediate to Advanced practice.

Answer

A stub provides canned answers to calls made during the test, while a mock is an object that you can make assertions about, such as verifying how many times a method was called.

Explanation

The core difference lies in the verification aspect. Why B is correct: A stub is used to provide a simple, fixed response (e.g., "when this method is called, return this value") to satisfy a dependency, allowing the test to run. You don't typically assert against the stub itself. A mock is more powerful; it can also provide responses, but its main purpose is to allow you to verify interactions (e.g., "assert that the SendEmail method was called exactly once with these specific arguments"). You use a mock when the behavior of the interaction is part of what you're testing. Why A is incorrect: They are distinct concepts, although often implemented using the same tools (mocking libraries). Why C is incorrect: Both techniques can be used in both unit and integration tests. Why D is incorrect: This reverses the roles. A mock is typically the more complex, behavior-verifying object.

Related Questions