解释如何 mock 容器服务以测试依赖注入逻辑
解读
在国内 Drupal 岗位面试中,这道题考察的是“能不能把 Symfony 依赖注入容器(DIC)里的服务替换成假对象,从而让单元测试既快又稳”。
面试官想听的不只是“用 PHPUnit 的 mock”,而是:
- Drupal 容器与 Symfony 容器的关系;
- 在测试环境下如何安全地“偷梁换柱”;
- 如何兼顾 KernelTestBase、WebTestBase、ExistingSite 等不同测试基类;
- 是否知道国内常见 CI(阿里云效、腾讯蓝盾、GitLab-CI)里跑测试时容器初始化的耗时痛点。
答得越深,越能体现“企业级交付”经验。
知识点
- Drupal 容器层级:
- DrupalKernel 在 bootstrap 阶段把 $container 存到 \Drupal::getContainer();
- 容器编译后默认 frozen,直接 set() 会抛 LogicException。
- 测试基类差异:
- UnitTestCase:不启数据库、不启内核,容器为 Null;
- KernelTestBase:启最小内核,容器可重写,但需配合 setUp() 中的 $this->container->set();
- BrowserTestBase / ExistingSite:整站启动,容器已 frozen,需用 Symfony DependencyInjection 的 compiler pass 或 Drupal 的 $settings['container_yamls'] 提前注入。
- 国内常用工具链:
- PHPUnit 9.5+(Drupal 9/10 官方要求);
- Prophecy 被官方移除,推荐 PHPUnit 原生 mock;
- 阿里云效缓存 /tmp/test-site-* 目录可缩短二次 bootstrap 时间。
- 安全规范:
- 禁止直接修改 prod 容器;
- mock 必须带 @group unit / @group kernel 隔离;
- 对核心服务(如 config.factory、database)mock 需审批,防止测试通过但生产爆炸。
答案
分场景给出可落地的 mock 方案,代码均基于 Drupal 10.2 + PHPUnit 9.6,国内 Composer 源可用阿里云镜像。
场景一:纯单元测试(UnitTestCase)
说明:此时容器未启动,直接 new 被测类并手动注入 mock 即可。
namespace Drupal\my_module\Tests\Unit;
use Drupal\my_module\OrderService;
use PHPUnit\Framework\TestCase;
final class OrderServiceTest extends TestCase {
public function testCalculateTotal(): void {
$priceLookup = $this->createMock(\Drupal\my_module\PriceLookupInterface::class);
$priceLookup->method('getPrice')
->with('SKU001')
->willReturn(99.99);
$sut = new OrderService($priceLookup);
$total = $sut->calculateTotal(['SKU001' => 2]);
$this->assertEquals(199.98, $total);
}
}
要点:
- 不依赖 \Drupal::service(),完全脱离容器;
- 国内 CI 中可开 Opcache 预加载,2000 个单元测试 30 秒跑完。
场景二:内核级测试(KernelTestBase)
说明:需要容器,但要把指定服务替换成 mock。
namespace Drupal\my_module\Tests\Kernel;
use Drupal\KernelTests\KernelTestBase;
final class PriceLookupIntegrationTest extends KernelTestBase {
protected static $modules = ['my_module', 'system'];
private $originalService;
protected function setUp(): void {
parent::setUp();
// 备份原服务
$this->originalService = $this->container->get('my_module.price_lookup');
}
public function testWithMockedPrice(): void {
$mock = $this->createMock(\Drupal\my_module\PriceLookupInterface::class);
$mock->method('getPrice')->willReturn(42.0);
// 容器尚未 frozen,可直接 set
$this->container->set('my_module.price_lookup', $mock);
// 调用被测代码
$total = \Drupal::service('my_module.order_service')->calculateTotal(['SKU002' => 1]);
$this->assertEquals(42.0, $total);
}
protected function tearDown(): void {
// 恢复现场,防止污染后续测试
$this->container->set('my_module.price_lookup', $this->originalService);
parent::tearDown();
}
}
要点:
- KernelTestBase 的容器在 setUp() 后仍处于可写状态;
- tearDown() 必须还原,否则并行测试(如阿里云效 4 并发)会串扰。
场景三:整站级测试(BrowserTestBase 或 ExistingSite)
说明:容器已编译并 frozen,直接 set() 会报错。
做法:通过 compiler pass 在测试专用 container YAML 里把服务 class 换成 fake。
步骤:
- 新建 tests/fixtures/test.services.yml
services:
my_module.price_lookup:
class: Drupal\my_module\Tests\Fixtures\FakePriceLookup
arguments: []
- 在测试类中注入该 YAML
protected function setUp(): void {
$settings['container_yamls'][] = __DIR__ . '/../../fixtures/test.services.yml';
parent::setUp();
}
- FakePriceLookup 实现同一接口,返回固定值。
要点:
- 国内政务项目常用此模式 mock 外部政务接口,避免测试网络抖动;
- 需把 fixtures 目录加入 .gitignore 防止污染生产。
场景四:对核心服务(如 config.factory)打桩
说明:国内银行项目常要求“单元测试不能读写数据库”。
做法:使用 Prophecy 或 PHPUnit 创建 stub,然后利用 KernelTestBase 的 $this->container->set() 替换。
$configStub = $this->createMock(\Drupal\Core\Config\ImmutableConfig::class);
$configStub->method('get')->willReturnMap([
['fee', 0.05],
]);
$configFactoryStub = $this->createMock(\Drupal\Core\Config\ConfigFactoryInterface::class);
$configFactoryStub->method('get')->with('my_module.settings')->willReturn($configStub);
$this->container->set('config.factory', $configFactoryStub);
注意:
- 国内监管要求测试报告可追溯,mock 对象必须在 @dataProvider 或 setUp() 中显式声明;
- 替换核心服务需团队架构师评审,防止测试掩盖真实风险。
拓展思考
- 并行化与性能:
国内阿里云效 4C8G 节点跑 Drupal 测试,瓶颈常在数据库。把容器 mock 后,配合 SQLite in-memory,可把 KernelTestBase 耗时从 45 秒降到 8 秒。 - 静态分析:
使用 PHPStan-Drupal 规则集,能提前发现“你把服务替换了,但接口签名对不上”的问题,减少 CodeReview 往返。 - 生产可观测性:
如果测试里 mock 了外部短信网关,上线前要在预发环境补一次“真调用”灰度,防止 mock 行为与真实服务商(如阿里云短信)不一致导致资损。 - 安全合规:
政府项目要求通过“等保 2.0”三级测评,测试代码里不能出现真实 AK/SK;mock 时把密钥字段打码,并配合 git-secrets 扫描,否则会被审计扣分。