What is the primary purpose of mocks and stubs in unit testing?

Get ready for your Object‑Oriented Programming Test. Use flashcards and multiple-choice questions. Each question includes hints and explanations. Prepare for your exam today!

Multiple Choice

What is the primary purpose of mocks and stubs in unit testing?

Explanation:
Mocks and stubs in unit testing are test doubles used to isolate the unit under test from its dependencies. By substituting real collaborators with these controlled substitutes, you can run tests that don’t depend on external systems or complex setups. A stub provides predetermined responses to calls from the unit, allowing the test to focus on the unit’s behavior without worrying about the actual behavior of the dependency. A mock goes a step further by also recording how the unit uses the dependency, so you can verify that specific interactions occurred (like calling a method with certain arguments). This isolation is what makes unit tests reliable and fast: they don’t suffer from network latency, database states, or other nondeterministic factors, and they can run repeatedly with predictable outcomes. It’s not about replacing production code or enforcing standards; it’s about creating a stable, controllable environment for testing the unit’s logic.

Mocks and stubs in unit testing are test doubles used to isolate the unit under test from its dependencies. By substituting real collaborators with these controlled substitutes, you can run tests that don’t depend on external systems or complex setups.

A stub provides predetermined responses to calls from the unit, allowing the test to focus on the unit’s behavior without worrying about the actual behavior of the dependency. A mock goes a step further by also recording how the unit uses the dependency, so you can verify that specific interactions occurred (like calling a method with certain arguments).

This isolation is what makes unit tests reliable and fast: they don’t suffer from network latency, database states, or other nondeterministic factors, and they can run repeatedly with predictable outcomes. It’s not about replacing production code or enforcing standards; it’s about creating a stable, controllable environment for testing the unit’s logic.