1. Mocking Services
Services are a primary target for mocking in Drupal tests. Here's how to mock a service:
// Create a mock service
$service = $this->createMock(MyServiceInterface::class);
$service->method('getData')
->willReturn(['mocked' => 'data']);
// Replace the service in the container
$this->container->set('my_service', $service);
2. Mocking the Entity API
Entity mocking is common in Drupal tests:
// Mock a node entity
$node = $this->createMock(NodeInterface::class);
$node->expects($this->once())
->method('getTitle')
->willReturn('Mocked Title');
3. Mocking the Database Layer
For unit tests, you often need to mock database interactions:
// Mock a database connection
$database = $this->createMock(Connection::class);
$statement = $this->createMock(\PDOStatement::class);
$statement->method('fetchAll')
->willReturn([['nid' => 1, 'title' => 'Test']]);
$database->method('query')
->willReturn($statement);
4. Mocking HTTP Requests
For external API interactions:
// Mock the HTTP client
$response = $this->createMock(ResponseInterface::class);
$response->method('getBody')
->willReturn(json_encode(['status' => 'success']));
$client = $this->createMock(ClientInterface::class);
$client->method('request')
->willReturn($response);