Intermediate LevelPHP 8+
How do you write unit tests with mock objects and method stubbing using PHPUnit?
❓ Interview Prompt: Explain PHPUnit test cases, mock objects ($this->createMock), method expectations (expects, with, willReturn), and testing isolated domain logic.
Unit testing requires isolating the class under test from external dependencies (databases, payment APIs) using Mock Objects.
PHPUnit Mocking Utilities:
•
'$this->createMock(Repository::class)': Generates a test double implementing all methods of the target class.
•
'$mock->expects($this->once())': Asserts how many times a method must be invoked during test execution.
•
'->method("find")->with(42)->willReturn($user)': Configures method stubs to return specific mock data when called with expected arguments.
Code Implementation Example
php
<?php
use PHPUnitFrameworkTestCase;
class UserServiceTest extends TestCase {
public function testGetUserByIdReturnsFormattedName(): void {
// 1. Create Mock object for UserRepository dependency
$userRepoMock = $this->createMock(UserRepository::class);
// 2. Configure method expectations and returned stub data
$userRepoMock->expects($this->once())
->method('find')
->with(42)
->willReturn(new User(42, 'Alice'));
// 3. Inject mock into service and assert behavior
$service = new UserService($userRepoMock);
$result = $service->getUserFormattedName(42);
$this->assertEquals('User #42: Alice', $result);
}
}💡Writing an isolated unit test using PHPUnit mock object expectations and stubbing.
🎯 Interview Key Takeaway
Use PHPUnit $this->createMock() to stub dependency methods and assert call expectations without touching external services.
#PHPUnit#Testing#Mocks#Intermediate
Back to all PHP 8+ Questions→