Sobes.tech
Middle

What are mocks and stubs? How do they differ?

sobes.tech AI

Answer from AI

Mocks and stubs are types of test doubles used in unit testing to simulate the behavior of real object dependencies.

Stub:

  • Provides "fake" behavior for a test scenario.
  • Responds to method calls with pre-defined values.
  • Does not verify interactions. Its purpose is to supply data to the tested object for further processing.

Mock:

  • Similar to a stub but with added interaction verification logic.
  • Contains expectations about which methods should be called, how many times, and with what arguments.
  • The test checks not only the result of the tested object but also the correctness of its interaction with the mock.
<?php
// Example of a stub object
class StubDatabase {
    public function getUserById(int $id): ?array {
        // Simulate return value for a specific ID
        if ($id === 1) {
            return ['id' => 1, 'name' => 'Test User'];
        }
        return null;
    }
}

Differences table:

Characteristic Stub Mock
Purpose Provide data for operation Verify interaction and data
Verification Does not verify interaction Checks how the object interacts with it
Behavior logic Simply returns values Contains call expectations
Who performs assert The tested object or client The mock itself (via expectations)
What are mocks and stubs? How do they differ? — PHP - sobes.tech