在 Symfony 容器中替换一个私有服务进行测试

Replace a private service in the Symfony container for testing

是否可以替换DI容器中的私有服务?我需要在我的测试环境中执行此操作,以便我可以 运行 集成测试,但仍然模拟对外部 API 的 HTTP 调用。

例如,我有为 HttpClientInterface 设置模拟的代码:

$response = new MockResponse('"some json body"');
$client = new MockHttpClient([$response]);
self::$container->set(HttpClientInterface::class, $client);

// Execute controller / command and perform assertions
// ...

我已经尝试使用下面的配置将 HttpClientInterface 定义为我的测试环境的 public 服务,但这不起作用,因为它不可实例化(它是一个接口)。

services:
  Symfony\Contracts\HttpClient\HttpClientInterface:
    public: true

我通过创建我自己的不需要在构造函数中设置响应的 MockHttpClient class 自己解决了这个问题。根据 Symfony 如何使容器不可变,在运行时替换容器中的服务似乎是错误的方法