Middle
Mis on mock ja stub? Kuidas nad erinevad?
sobes.tech AI
Vastus AI-lt
Mocks and stubs are types of test doubles used in unit testing to simulate the behavior of real dependencies of an object.
Stub:
- Provides "placeholder" behavior for a test scenario.
- Responds to method calls by returning predefined 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 but also the correctness of the interaction with the mock.
<?php
// Example of a mock object
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
class UserServiceTest extends TestCase {
public function testGetUserByIdCallsDatabase(): void {
$databaseMock = $this->createMock(Database::class);
$databaseMock->expects($this->once()) // Expect one call
->method('getUserById')
->with(1) // Expect argument 1
->willReturn(['id' => 1, 'name' => 'Test User']); // Expected return value
$userService = new UserService($databaseMock);
$user = $userService->getUserById(1);
// Verify result and interaction via mock
$this->assertNotEmpty($user);
$this->assertEquals('Test User', $user['name']);
}
}
Differences in the table:
| Characteristic | Stub | Mock |
|---|---|---|
| Purpose | Provide data for operation | Verify interaction and data |
| Verification | Does not verify interactions | Checks how the object interacts |
| Behavior logic | Simply returns values | Contains call expectations |
Who performs assert |
The tested object or client | The mock itself (via expectations) |